file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
./full_match/1/0x184e48FA8B332D3D3FB08eDa535Fd7591e340Bb2/sources/contracts/NFT/ERC721M.sol
* ____________________________________________________________________________________________________________________ -->GETTER @dev (function) totalBurned Returns the count of tokens sent to the burn address --------------------------------------------------------------------------------------------------------------------- @return totalBurned_ The total burned supply of this collection --------------------------------------------------------------------------------------------------------------------- _____________________________________________________________________________________________________________________/
function totalBurned() external view virtual returns (uint256 totalBurned_) { }
4,934,978
[ 1, 21157, 21157, 21157, 21157, 21157, 21157, 21157, 7198, 28524, 4766, 2398, 15431, 7113, 11976, 225, 261, 915, 13, 2078, 38, 321, 329, 225, 2860, 326, 1056, 434, 2430, 3271, 358, 326, 18305, 1758, 8879, 9634, 553, 327, 2078, 38, 321, 329, 67, 282, 1021, 2078, 18305, 329, 14467, 434, 333, 1849, 8879, 9634, 553, 389, 21157, 21157, 21157, 21157, 21157, 21157, 21157, 7198, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2078, 38, 321, 329, 1435, 3903, 1476, 5024, 1135, 261, 11890, 5034, 2078, 38, 321, 329, 67, 13, 288, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /** * @title Toft Standard Token (TST) * @author: Muhammad Zaryab Khan * Developed By: BLOCK360 * Date: Septemeber 08, 2020 * Version: 2.0 */ pragma solidity 0.6.2; /** * @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" ); } } /** * @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)); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } interface ITST { /** * @dev sets existing feeAccount to `feeAccount` by the caller. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {FeeAccountUpdated} event indicating the new FeeAccount. */ function setFeeAccount(address feeAccount) external returns (bool); /** * @dev sets existing maxTransferFee to `_maxTransferFee` by the caller. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {MaxTransferFeeUpdated} event indicating the new maximum transfer fee. */ function setMaxTransferFee(uint256 maxTransferFee) external returns (bool); /** * @dev sets existing minTransferFee to `_minTransferFee` by the caller. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {MinTransferFeeUpdated} event indicating the new minimum transfer fee. */ function setMinTransferFee(uint256 minTransferFee) external returns (bool); /** * @dev sets existing transferFeePercentage to `_transferFeePercentage` by the caller. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {TransferFeePercentageUpdated} event indicating the new percentange transfer fee. */ function setTransferFeePercentage(uint256 transferFeePercentage) external returns (bool); /** * @dev calculate transfer fee aginst `weiAmount`. * @param weiAmount Value in wei to be to calculate fee. * @return Number of tokens in wei to paid for transfer fee. */ function calculateTransferFee(uint256 weiAmount) external view returns (uint256); /** * @return the current fee account collector. */ function feeAccount() external view returns (address); /** * @return the current maximum transfer fee. */ function maxTransferFee() external view returns (uint256); /** * @return the current minimum transfer fee. */ function minTransferFee() external view returns (uint256); /** * @return the current percentange of transfer fee. */ function transferFeePercentage() external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient` with a transaction note `message`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer( address recipient, uint256 amount, string calldata message ) 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, string calldata message ) external returns (bool); /** * emit once on contract creatsion */ event Created(); /** * Event for FeeAccount update. * @param newFeeAccount new FeeAccount. * @param previousFeeAccount old FeeAccount. */ event FeeAccountUpdated( address indexed previousFeeAccount, address indexed newFeeAccount ); /** * Event for MaxTransferFee update. * @param newMaxTransferFee new maximum tranfer fee. * @param previousMaxTransferFee old maximum tranfer fee. */ event MaxTransferFeeUpdated( uint256 previousMaxTransferFee, uint256 newMaxTransferFee ); /** * Event for MinTransferFee update. * @param newMinTransferFee new minimum tranfer fee. * @param previousMinTransferFee old minimum tranfer fee. */ event MinTransferFeeUpdated( uint256 previousMinTransferFee, uint256 newMinTransferFee ); /** * Event for TransferFeePercentage update. * @param newTransferFeePercentage new percentange tranfer fee. * @param previousTransferFeePercentage old percentange tranfer fee. */ event TransferFeePercentageUpdated( uint256 previousTransferFeePercentage, uint256 newTransferFeePercentage ); /** * @dev emitted with token transfer is done. * @param from the account from which tokens are moved. * @param to the recipient of tokens. * @param value the amount to tokens moved. * @param fee the account to fee deducted from `from`. * @param timestamp current block timestamp. */ event Transfer( address indexed from, address indexed to, uint256 value, uint256 fee, string description, uint256 timestamp ); } /** * @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 virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } 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; } /** * @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 PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @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. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } /** * @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, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer {} 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 `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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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; } /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns (bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal virtual view returns (bytes memory); function versionRecipient() external virtual view returns (string memory); } /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns (bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual override view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal virtual override view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize(), 20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr, 32), size) calldatacopy(add(ptr, 64), 0, size) return(ptr, add(size, 64)) } } else { return msg.data; } } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[44] private __gap; } /** * @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 ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe { 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; } /** * @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 ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe { 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 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20: burn amount exceeds allowance" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } /* * TransferFee * Base contract for trasfer fee specification. */ abstract contract TransferFee is OwnableUpgradeSafe, ITST { address private _feeAccount; uint256 private _maxTransferFee; uint256 private _minTransferFee; uint256 private _transferFeePercentage; /** * @dev Sets the value, _feeAccount that collects tranfer fee, fee percentange, maximum, minimum amount of wei for trasfer fee. * @param feeAccount account that collects fee. * @param minTransferFee Min amount of wei to be charged on trasfer. * @param minTransferFee Min amount of wei to be charged on trasfer. * @param transferFeePercentage Percent amount of wei to be charged on trasfer. */ function __TransferFee_init_unchained( address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint256 transferFeePercentage ) public { require(feeAccount != address(0x0), "TransferFee: feeAccount is 0"); // this also handles "minTransferFee should be less than maxTransferFee" // solhint-disable-next-line max-line-length require( maxTransferFee >= minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee" ); __Ownable_init_unchained(); _feeAccount = feeAccount; _maxTransferFee = maxTransferFee; _minTransferFee = minTransferFee; _transferFeePercentage = transferFeePercentage; } /** * See {ITrasnferFee-setFeeAccount}. * * @dev sets `feeAccount` to `_feeAccount` by the caller. * * Requirements: * * - `feeAccount` cannot be the zero. */ function setFeeAccount(address feeAccount) external override onlyOwner returns (bool) { require(feeAccount != address(0x0), "TransferFee: feeAccount is 0"); emit FeeAccountUpdated(_feeAccount, feeAccount); _feeAccount = feeAccount; return true; } /** * See {ITrasnferFee-setMaxTransferFee}. * * @dev sets `maxTransferFee` to `_maxTransferFee` by the caller. * * Requirements: * * - `maxTransferFee` cannot be the zero. * - `maxTransferFee` should be greater than minTransferFee. */ function setMaxTransferFee(uint256 maxTransferFee) external override onlyOwner returns (bool) { // solhint-disable-next-line max-line-length require( maxTransferFee >= _minTransferFee, "TransferFee: maxTransferFee should be greater or equal to minTransferFee" ); emit MaxTransferFeeUpdated(_maxTransferFee, maxTransferFee); _maxTransferFee = maxTransferFee; return true; } /** * See {ITrasnferFee-setMinTransferFee}. * * @dev sets `minTransferFee` to `_minTransferFee` by the caller. * * Requirements: * * - `minTransferFee` cannot be the zero. * - `minTransferFee` should be less than maxTransferFee. */ function setMinTransferFee(uint256 minTransferFee) external override onlyOwner returns (bool) { // solhint-disable-next-line max-line-length require( minTransferFee <= _maxTransferFee, "TransferFee: minTransferFee should be less than maxTransferFee" ); emit MaxTransferFeeUpdated(_minTransferFee, minTransferFee); _minTransferFee = minTransferFee; return true; } /** * See {ITrasnferFee-setTransferFeePercentage}. * * @dev sets `transferFeePercentage` to `_transferFeePercentage` by the caller. * * Requirements: * * - `transferFeePercentage` cannot be the zero. * - `transferFeePercentage` should be less than maxTransferFee. */ function setTransferFeePercentage(uint256 transferFeePercentage) external override onlyOwner returns (bool) { emit TransferFeePercentageUpdated( _transferFeePercentage, transferFeePercentage ); _transferFeePercentage = transferFeePercentage; return true; } /** * @dev See {ITrasnferFee-feeAccount}. */ function feeAccount() public override view returns (address) { return _feeAccount; } /** * See {ITrasnferFee-maxTransferFee}. */ function maxTransferFee() public override view returns (uint256) { return _maxTransferFee; } /** * See {ITrasnferFee-minTransferFee}. */ function minTransferFee() public override view returns (uint256) { return _minTransferFee; } /** * See {ITrasnferFee-transferFeePercentage}. */ function transferFeePercentage() public override view returns (uint256) { return _transferFeePercentage; } uint256[50] private __gap; } /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to aother accounts */ /** * @dev TST implementation: * - charge fee on token transfer * - ability for owner to burn (destroy) tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers */ contract TST is Initializable, ContextUpgradeSafe, OwnableUpgradeSafe, AccessControlUpgradeSafe, ERC20BurnableUpgradeSafe, ERC20PausableUpgradeSafe, BaseRelayRecipient, TransferFee { string public version; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20, TransferFee-constructor}. */ function initialize( string memory name, string memory symbol, address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint256 transferFeePercentage ) public { __TST_init( name, symbol, feeAccount, maxTransferFee, minTransferFee, transferFeePercentage ); } function __TST_init( string memory name, string memory symbol, address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint256 transferFeePercentage ) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained(name, symbol); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); __TST_init_unchained(); __TransferFee_init_unchained( feeAccount, maxTransferFee, minTransferFee, transferFeePercentage ); } function __TST_init_unchained() internal initializer { version = "2.0"; _setupDecimals(2); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(BURNER_ROLE, _msgSender()); emit Created(); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require( hasRole(MINTER_ROLE, _msgSender()), "TST: must have minter role to mint" ); require( to == owner(), "TST: tokens can be only minted on owner address" ); _mint(to, amount); } /** * @dev overloading burn function to enable token burn from any account * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. * Requirements: * * - the caller must have the `BURNER_ROLE`. */ function burn(address account, uint256 amount) public virtual { require( hasRole(BURNER_ROLE, _msgSender()), "TST: must have burner role to burn" ); _burn(account, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public { require( hasRole(PAUSER_ROLE, _msgSender()), "TST: must have pauser role to pause" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public { require( hasRole(PAUSER_ROLE, _msgSender()), "TST: must have pauser role to unpause" ); _unpause(); } /** * @dev override IERC20-transfer to deducted transfer fee from `amount` * @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(ERC20UpgradeSafe) returns (bool) { require( recipient != address(this), "ERC20: transfer to the this contract" ); uint256 _fee = calculateTransferFee(amount); // calling ERC20 transfer function to transfer tokens super.transfer(recipient, amount); // TST if (_fee > 0) super.transfer(feeAccount(), _fee); // transfering fee to fee account emit Transfer(_msgSender(), recipient, amount, _fee, "", now); return true; } /** * @dev overriding version of ${transfer} that includes message in token transfer * */ function transfer( address recipient, uint256 amount, string memory message ) public virtual override(ITST) returns (bool) { require( recipient != address(this), "ERC20: transfer to the this contract" ); uint256 _fee = calculateTransferFee(amount); // calling ERC20 transfer function to transfer tokens super.transfer(recipient, amount); // TST if (_fee > 0) super.transfer(feeAccount(), _fee); // transfering fee to fee account emit Transfer(_msgSender(), recipient, amount, _fee, message, now); 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(ERC20UpgradeSafe) returns (bool) { require( recipient != address(this), "ERC20: transfer to the this contract" ); uint256 _fee = calculateTransferFee(amount); // calling ERC20 transfer function to transfer tokens super.transferFrom(sender, recipient, amount); // TST if (_fee > 0) super.transferFrom(sender, feeAccount(), _fee); // transfering fee to fee account emit Transfer(sender, recipient, amount, _fee, "", now); return true; } /** * @dev overriding version of ${transferFrom} that includes message in token transfer * */ function transferFrom( address sender, address recipient, uint256 amount, string memory message ) public virtual override(ITST) returns (bool) { require( recipient != address(this), "ERC20: transfer to the this contract" ); uint256 _fee = calculateTransferFee(amount); // calling ERC20 transfer function to transfer tokens super.transferFrom(sender, recipient, amount); // TST if (_fee > 0) super.transferFrom(sender, feeAccount(), _fee); // transfering fee to fee account emit Transfer(sender, recipient, amount, _fee, message, now); return true; } /** * @dev calculate transfer fee aginst `weiAmount`. * @param weiAmount Value in wei to be to calculate fee. * @return Number of tokens in wei to paid for transfer fee. */ function calculateTransferFee(uint256 weiAmount) public virtual override(ITST) view returns (uint256) { uint256 divisor = uint256(100).mul((10**uint256(decimals()))); uint256 _fee = (transferFeePercentage().mul(weiAmount)).div(divisor); if (_fee < minTransferFee()) { _fee = minTransferFee(); } else if (_fee > maxTransferFee()) { _fee = maxTransferFee(); } return _fee; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20UpgradeSafe, ERC20PausableUpgradeSafe) { super._beforeTokenTransfer(from, to, amount); } //============================== GSN Functions ============================== function setTrustedForwarder(address forwarder) external onlyOwner { trustedForwarder = forwarder; } function _msgSender() internal override(BaseRelayRecipient, ContextUpgradeSafe) view returns (address payable) { return BaseRelayRecipient._msgSender(); } function _msgData() internal override(BaseRelayRecipient, ContextUpgradeSafe) view returns (bytes memory) { return BaseRelayRecipient._msgData(); } function versionRecipient() external override view returns (string memory) { return "2.0.0"; } //============================== Legacy Functions ============================== function increaseSupply(address target, uint256 amount) external virtual { mint(target, amount); } function decreaseSupply(address target, uint256 amount) external virtual { burn(target, amount); } function getOwner() external view returns (address) { return owner(); } function getName() external view returns (string memory) { return name(); } function getFeeAccount() external view returns (address) { return feeAccount(); } function getTotalSupply() external view returns (uint256) { return totalSupply(); } function getMaxTransferFee() external view returns (uint256) { return maxTransferFee(); } function getMinTransferFee() external view returns (uint256) { return minTransferFee(); } function getTransferFeePercentage() external view returns (uint256) { return transferFeePercentage(); } function getBalance(address balanceAddress) external virtual view returns (uint256) { return balanceOf(balanceAddress); } uint256[50] private __gap; }
* A base contract to be inherited by any contract that want to receive relayed transactions A subclass must use "_msgSender()" instead of "msg.sender"/
abstract contract BaseRelayRecipient is IRelayRecipient { address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns (bool) } { return forwarder == trustedForwarder; } function _msgSender() internal virtual override view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { assembly { ret := shr(96, calldataload(sub(calldatasize(), 20))) } return msg.sender; } } function _msgSender() internal virtual override view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { assembly { ret := shr(96, calldataload(sub(calldatasize(), 20))) } return msg.sender; } } function _msgSender() internal virtual override view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { assembly { ret := shr(96, calldataload(sub(calldatasize(), 20))) } return msg.sender; } } } else { function _msgData() internal virtual override view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { assembly { let ptr := mload(0x40) let size := sub(calldatasize(), 20) mstore(ptr, 0x20) mstore(add(ptr, 32), size) calldatacopy(add(ptr, 64), 0, size) return(ptr, add(size, 64)) } return msg.data; } } function _msgData() internal virtual override view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { assembly { let ptr := mload(0x40) let size := sub(calldatasize(), 20) mstore(ptr, 0x20) mstore(add(ptr, 32), size) calldatacopy(add(ptr, 64), 0, size) return(ptr, add(size, 64)) } return msg.data; } } function _msgData() internal virtual override view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { assembly { let ptr := mload(0x40) let size := sub(calldatasize(), 20) mstore(ptr, 0x20) mstore(add(ptr, 32), size) calldatacopy(add(ptr, 64), 0, size) return(ptr, add(size, 64)) } return msg.data; } } } else { }
6,588,876
[ 1, 37, 1026, 6835, 358, 506, 12078, 635, 1281, 6835, 716, 2545, 358, 6798, 18874, 329, 8938, 432, 10177, 1297, 999, 4192, 3576, 12021, 10031, 3560, 434, 315, 3576, 18, 15330, 6, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 3360, 27186, 18241, 353, 467, 27186, 18241, 288, 203, 565, 1758, 1071, 13179, 30839, 31, 203, 203, 565, 445, 353, 16950, 30839, 12, 2867, 364, 20099, 13, 203, 3639, 1071, 203, 3639, 3849, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 97, 203, 565, 288, 203, 3639, 327, 364, 20099, 422, 13179, 30839, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 12021, 1435, 203, 3639, 2713, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 8843, 429, 325, 13, 203, 565, 288, 203, 3639, 309, 261, 3576, 18, 892, 18, 2469, 1545, 4248, 597, 353, 16950, 30839, 12, 3576, 18, 15330, 3719, 288, 203, 5411, 19931, 288, 203, 7734, 325, 519, 699, 86, 12, 10525, 16, 745, 72, 3145, 6189, 12, 1717, 12, 1991, 13178, 554, 9334, 4200, 20349, 203, 5411, 289, 203, 5411, 327, 1234, 18, 15330, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 12021, 1435, 203, 3639, 2713, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 8843, 429, 325, 13, 203, 565, 288, 203, 3639, 309, 261, 3576, 18, 892, 18, 2469, 1545, 4248, 597, 353, 16950, 30839, 12, 3576, 18, 15330, 3719, 288, 203, 5411, 19931, 288, 203, 7734, 325, 519, 699, 86, 12, 10525, 16, 745, 72, 3145, 6189, 12, 1717, 12, 1991, 13178, 554, 9334, 4200, 20349, 203, 5411, 289, 203, 5411, 327, 1234, 18, 15330, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-04 */ pragma solidity 0.6.7; abstract contract DSValueLike { function getResultWithValidity() virtual external view returns (uint256, bool); } abstract contract FSMWrapperLike { function renumerateCaller(address) virtual external; } contract OSM { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "OSM/account-not-authorized"); _; } // --- Stop --- uint256 public stopped; modifier stoppable { require(stopped == 0, "OSM/is-stopped"); _; } // --- Variables --- address public priceSource; uint16 constant ONE_HOUR = uint16(3600); uint16 public updateDelay = ONE_HOUR; uint64 public lastUpdateTime; // --- Structs --- struct Feed { uint128 value; uint128 isValid; } Feed currentFeed; Feed nextFeed; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 parameter, uint256 val); event ModifyParameters(bytes32 parameter, address val); event Start(); event Stop(); event ChangePriceSource(address priceSource); event ChangeDelay(uint16 delay); event RestartValue(); event UpdateResult(uint256 newMedian, uint256 lastUpdateTime); constructor (address priceSource_) public { authorizedAccounts[msg.sender] = 1; priceSource = priceSource_; if (priceSource != address(0)) { (uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate(); if (hasValidValue) { nextFeed = Feed(uint128(uint(priceFeedValue)), 1); currentFeed = nextFeed; lastUpdateTime = latestUpdateTime(currentTime()); emit UpdateResult(uint(currentFeed.value), lastUpdateTime); } } emit AddAuthorization(msg.sender); emit ChangePriceSource(priceSource); } // --- Math --- function addition(uint64 x, uint64 y) internal pure returns (uint64 z) { z = x + y; require(z >= x); } // --- Core Logic --- /* * @notify Stop the OSM */ function stop() external isAuthorized { stopped = 1; emit Stop(); } /* * @notify Start the OSM */ function start() external isAuthorized { stopped = 0; emit Start(); } /* * @notify Change the oracle from which the OSM reads * @param priceSource_ The address of the oracle from which the OSM reads */ function changePriceSource(address priceSource_) external isAuthorized { priceSource = priceSource_; emit ChangePriceSource(priceSource); } /* * @notify Helper that returns the current block timestamp */ function currentTime() internal view returns (uint) { return block.timestamp; } /* * @notify Return the latest update time * @param timestamp Custom reference timestamp to determine the latest update time from */ function latestUpdateTime(uint timestamp) internal view returns (uint64) { require(updateDelay != 0, "OSM/update-delay-is-zero"); return uint64(timestamp - (timestamp % updateDelay)); } /* * @notify Change the delay between updates * @param delay The new delay */ function changeDelay(uint16 delay) external isAuthorized { require(delay > 0, "OSM/delay-is-zero"); updateDelay = delay; emit ChangeDelay(updateDelay); } /* * @notify Restart/set to zero the feeds stored in the OSM */ function restartValue() external isAuthorized { currentFeed = nextFeed = Feed(0, 0); stopped = 1; emit RestartValue(); } /* * @notify View function that returns whether the delay between calls has been passed */ function passedDelay() public view returns (bool ok) { return currentTime() >= uint(addition(lastUpdateTime, uint64(updateDelay))); } /* * @notify Update the price feeds inside the OSM */ function updateResult() virtual external stoppable { // Check if the delay passed require(passedDelay(), "OSM/not-passed"); // Read the price from the median (uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate(); // If the value is valid, update storage if (hasValidValue) { // Update state currentFeed = nextFeed; nextFeed = Feed(uint128(uint(priceFeedValue)), 1); lastUpdateTime = latestUpdateTime(currentTime()); // Emit event emit UpdateResult(uint(currentFeed.value), lastUpdateTime); } } // --- Getters --- /* * @notify Internal helper that reads a price and its validity from the priceSource */ function getPriceSourceUpdate() internal view returns (uint256, bool) { try DSValueLike(priceSource).getResultWithValidity() returns (uint256 priceFeedValue, bool hasValidValue) { return (priceFeedValue, hasValidValue); } catch(bytes memory) { return (0, false); } } /* * @notify Return the current feed value and its validity */ function getResultWithValidity() external view returns (uint256,bool) { return (uint(currentFeed.value), currentFeed.isValid == 1); } /* * @notify Return the next feed's value and its validity */ function getNextResultWithValidity() external view returns (uint256,bool) { return (nextFeed.value, nextFeed.isValid == 1); } /* * @notify Return the current feed's value only if it's valid, otherwise revert */ function read() external view returns (uint256) { require(currentFeed.isValid == 1, "OSM/no-current-value"); return currentFeed.value; } } contract ExternallyFundedOSM is OSM { // --- Variables --- FSMWrapperLike public fsmWrapper; // --- Evemts --- event FailRenumerateCaller(address wrapper, address caller); constructor (address priceSource_) public OSM(priceSource_) {} // --- Administration --- /* * @notify Modify an address parameter * @param parameter The parameter name * @param val The new value for the parameter */ function modifyParameters(bytes32 parameter, address val) external isAuthorized { if (parameter == "fsmWrapper") { require(val != address(0), "ExternallyFundedOSM/invalid-fsm-wrapper"); fsmWrapper = FSMWrapperLike(val); } else revert("ExternallyFundedOSM/modify-unrecognized-param"); emit ModifyParameters(parameter, val); } /* * @notify Update the price feeds inside the OSM */ function updateResult() override external stoppable { // Check if the delay passed require(passedDelay(), "ExternallyFundedOSM/not-passed"); // Check that the wrapper is set require(address(fsmWrapper) != address(0), "ExternallyFundedOSM/null-wrapper"); // Read the price from the median (uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate(); // If the value is valid, update storage if (hasValidValue) { // Update state currentFeed = nextFeed; nextFeed = Feed(uint128(uint(priceFeedValue)), 1); lastUpdateTime = latestUpdateTime(currentTime()); // Emit event emit UpdateResult(uint(currentFeed.value), lastUpdateTime); // Pay the caller try fsmWrapper.renumerateCaller(msg.sender) {} catch(bytes memory revertReason) { emit FailRenumerateCaller(address(fsmWrapper), msg.sender); } } } } contract GebMath { uint256 public constant RAY = 10 ** 27; uint256 public constant WAD = 10 ** 18; function ray(uint x) public pure returns (uint z) { z = multiply(x, 10 ** 9); } function rad(uint x) public pure returns (uint z) { z = multiply(x, 10 ** 27); } function minimum(uint x, uint y) public pure returns (uint z) { z = (x <= y) ? x : y; } function addition(uint x, uint y) public pure returns (uint z) { z = x + y; require(z >= x, "uint-uint-add-overflow"); } function subtract(uint x, uint y) public pure returns (uint z) { z = x - y; require(z <= x, "uint-uint-sub-underflow"); } function multiply(uint x, uint y) public pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "uint-uint-mul-overflow"); } function rmultiply(uint x, uint y) public pure returns (uint z) { z = multiply(x, y) / RAY; } function rdivide(uint x, uint y) public pure returns (uint z) { z = multiply(x, RAY) / y; } function wdivide(uint x, uint y) public pure returns (uint z) { z = multiply(x, WAD) / y; } function wmultiply(uint x, uint y) public pure returns (uint z) { z = multiply(x, y) / WAD; } function rpower(uint x, uint n, uint base) public pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } } abstract contract StabilityFeeTreasuryLike { function getAllowance(address) virtual external view returns (uint, uint); function systemCoin() virtual external view returns (address); function pullFunds(address, address, uint) virtual external; function setTotalAllowance(address, uint256) external virtual; function setPerBlockAllowance(address, uint256) external virtual; } contract NoSetupIncreasingTreasuryReimbursement is GebMath { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "NoSetupIncreasingTreasuryReimbursement/account-not-authorized"); _; } // --- Variables --- // Starting reward for the fee receiver/keeper uint256 public baseUpdateCallerReward; // [wad] // Max possible reward for the fee receiver/keeper uint256 public maxUpdateCallerReward; // [wad] // Max delay taken into consideration when calculating the adjusted reward uint256 public maxRewardIncreaseDelay; // [seconds] // Rate applied to baseUpdateCallerReward every extra second passed beyond a certain point (e.g next time when a specific function needs to be called) uint256 public perSecondCallerRewardIncrease; // [ray] // SF treasury StabilityFeeTreasuryLike public treasury; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters( bytes32 parameter, address addr ); event ModifyParameters( bytes32 parameter, uint256 val ); event FailRewardCaller(bytes revertReason, address feeReceiver, uint256 amount); constructor() public { authorizedAccounts[msg.sender] = 1; maxRewardIncreaseDelay = uint(-1); emit AddAuthorization(msg.sender); } // --- Boolean Logic --- function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- Treasury --- /** * @notice This returns the stability fee treasury allowance for this contract by taking the minimum between the per block and the total allowances **/ function treasuryAllowance() public view returns (uint256) { (uint total, uint perBlock) = treasury.getAllowance(address(this)); return minimum(total, perBlock); } /* * @notice Get the SF reward that can be sent to a function caller right now * @param timeOfLastUpdate The last time when the function that the treasury pays for has been updated * @param defaultDelayBetweenCalls Enforced delay between calls to the function for which the treasury reimburses callers */ function getCallerReward(uint256 timeOfLastUpdate, uint256 defaultDelayBetweenCalls) public view returns (uint256) { // If the rewards are null or if the time of the last update is in the future or present, return 0 bool nullRewards = (baseUpdateCallerReward == 0 && maxUpdateCallerReward == 0); if (either(timeOfLastUpdate >= now, nullRewards)) return 0; // If the time elapsed is smaller than defaultDelayBetweenCalls or if the base reward is zero, return 0 uint256 timeElapsed = (timeOfLastUpdate == 0) ? defaultDelayBetweenCalls : subtract(now, timeOfLastUpdate); if (either(timeElapsed < defaultDelayBetweenCalls, baseUpdateCallerReward == 0)) { return 0; } // If too much time elapsed, return the max reward uint256 adjustedTime = subtract(timeElapsed, defaultDelayBetweenCalls); uint256 maxPossibleReward = minimum(maxUpdateCallerReward, treasuryAllowance() / RAY); if (adjustedTime > maxRewardIncreaseDelay) { return maxPossibleReward; } // Calculate the reward uint256 calculatedReward = baseUpdateCallerReward; if (adjustedTime > 0) { calculatedReward = rmultiply(rpower(perSecondCallerRewardIncrease, adjustedTime, RAY), calculatedReward); } // If the reward is higher than max, set it to max if (calculatedReward > maxPossibleReward) { calculatedReward = maxPossibleReward; } return calculatedReward; } /** * @notice Send a stability fee reward to an address * @param proposedFeeReceiver The SF receiver * @param reward The system coin amount to send **/ function rewardCaller(address proposedFeeReceiver, uint256 reward) internal { // If the receiver is the treasury itself or if the treasury is null or if the reward is zero, return if (address(treasury) == proposedFeeReceiver) return; if (either(address(treasury) == address(0), reward == 0)) return; // Determine the actual receiver and send funds address finalFeeReceiver = (proposedFeeReceiver == address(0)) ? msg.sender : proposedFeeReceiver; try treasury.pullFunds(finalFeeReceiver, treasury.systemCoin(), reward) {} catch(bytes memory revertReason) { emit FailRewardCaller(revertReason, finalFeeReceiver, reward); } } } abstract contract FSMLike { function stopped() virtual public view returns (uint256); function priceSource() virtual public view returns (address); function updateDelay() virtual public view returns (uint16); function lastUpdateTime() virtual public view returns (uint64); function newPriceDeviation() virtual public view returns (uint256); function passedDelay() virtual public view returns (bool); function getNextBoundedPrice() virtual public view returns (uint128); function getNextPriceLowerBound() virtual public view returns (uint128); function getNextPriceUpperBound() virtual public view returns (uint128); function getResultWithValidity() virtual external view returns (uint256, bool); function getNextResultWithValidity() virtual external view returns (uint256, bool); function read() virtual external view returns (uint256); } contract FSMWrapper is NoSetupIncreasingTreasuryReimbursement { // --- Vars --- // When the rate has last been relayed uint256 public lastReimburseTime; // [timestamp] // Enforced gap between reimbursements uint256 public reimburseDelay; // [seconds] FSMLike public fsm; constructor(address fsm_, uint256 reimburseDelay_) public NoSetupIncreasingTreasuryReimbursement() { require(fsm_ != address(0), "FSMWrapper/null-fsm"); fsm = FSMLike(fsm_); reimburseDelay = reimburseDelay_; emit ModifyParameters("reimburseDelay", reimburseDelay); } // --- Administration --- /* * @notice Change the addresses of contracts that this wrapper is connected to * @param parameter The contract whose address is changed * @param addr The new contract address */ function modifyParameters(bytes32 parameter, address addr) external isAuthorized { require(addr != address(0), "FSMWrapper/null-addr"); if (parameter == "fsm") { fsm = FSMLike(addr); } else if (parameter == "treasury") { require(StabilityFeeTreasuryLike(addr).systemCoin() != address(0), "FSMWrapper/treasury-coin-not-set"); treasury = StabilityFeeTreasuryLike(addr); } else revert("FSMWrapper/modify-unrecognized-param"); emit ModifyParameters( parameter, addr ); } /* * @notify Modify a uint256 parameter * @param parameter The parameter name * @param val The new parameter value */ function modifyParameters(bytes32 parameter, uint256 val) external isAuthorized { if (parameter == "baseUpdateCallerReward") { require(val <= maxUpdateCallerReward, "FSMWrapper/invalid-base-caller-reward"); baseUpdateCallerReward = val; } else if (parameter == "maxUpdateCallerReward") { require(val >= baseUpdateCallerReward, "FSMWrapper/invalid-max-caller-reward"); maxUpdateCallerReward = val; } else if (parameter == "perSecondCallerRewardIncrease") { require(val >= RAY, "FSMWrapper/invalid-caller-reward-increase"); perSecondCallerRewardIncrease = val; } else if (parameter == "maxRewardIncreaseDelay") { require(val > 0, "FSMWrapper/invalid-max-increase-delay"); maxRewardIncreaseDelay = val; } else if (parameter == "reimburseDelay") { reimburseDelay = val; } else revert("FSMWrapper/modify-unrecognized-param"); emit ModifyParameters( parameter, val ); } // --- Renumeration Logic --- /* * @notice Renumerate the caller that updates the connected FSM * @param feeReceiver The address that will receive the reward for the update */ function renumerateCaller(address feeReceiver) external { // Perform checks require(address(fsm) == msg.sender, "FSMWrapper/invalid-caller"); require(feeReceiver != address(0), "FSMWrapper/null-fee-receiver"); // Check delay between calls require(either(subtract(now, lastReimburseTime) >= reimburseDelay, lastReimburseTime == 0), "FSMWrapper/wait-more"); // Get the caller's reward uint256 callerReward = getCallerReward(lastReimburseTime, reimburseDelay); // Store the timestamp of the update lastReimburseTime = now; // Pay the caller for updating the FSM rewardCaller(feeReceiver, callerReward); } // --- Wrapped Functionality --- /* * @notify Return whether the FSM is stopped */ function stopped() public view returns (uint256) { return fsm.stopped(); } /* * @notify Return the FSM price source */ function priceSource() public view returns (address) { return fsm.priceSource(); } /* * @notify Return the FSM update delay */ function updateDelay() public view returns (uint16) { return fsm.updateDelay(); } /* * @notify Return the FSM last update time */ function lastUpdateTime() public view returns (uint64) { return fsm.lastUpdateTime(); } /* * @notify Return the FSM's next price deviation */ function newPriceDeviation() public view returns (uint256) { return fsm.newPriceDeviation(); } /* * @notify Return whether the update delay has been passed in the FSM */ function passedDelay() public view returns (bool) { return fsm.passedDelay(); } /* * @notify Return the next bounded price from the FSM */ function getNextBoundedPrice() public view returns (uint128) { return fsm.getNextBoundedPrice(); } /* * @notify Return the next lower bound price from the FSM */ function getNextPriceLowerBound() public view returns (uint128) { return fsm.getNextPriceLowerBound(); } /* * @notify Return the next upper bound price from the FSM */ function getNextPriceUpperBound() public view returns (uint128) { return fsm.getNextPriceUpperBound(); } /* * @notify Return the result with its validity from the FSM */ function getResultWithValidity() external view returns (uint256, bool) { (uint256 price, bool valid) = fsm.getResultWithValidity(); return (price, valid); } /* * @notify Return the next result with its validity from the FSM */ function getNextResultWithValidity() external view returns (uint256, bool) { (uint256 price, bool valid) = fsm.getNextResultWithValidity(); return (price, valid); } /* * @notify Return the result from the FSM if it's valid */ function read() external view returns (uint256) { return fsm.read(); } } abstract contract LiquidationEngineLike { function addAuthorization(address) external virtual; } abstract contract FsmGovernanceInterfaceLike { function setFsm(bytes32, address) external virtual; } abstract contract OracleRelayerLike { function modifyParameters(bytes32, bytes32, address) external virtual; } // @notice Proposal to deploy and setup new OSM and wrapper // Missing steps: // - Change orcl for the targeted collateral in the OracleRelayer // - Change collateralFSM in the collateral's auction house contract DeployOSMandWrapper { // --- Variables --- uint256 public constant RAY = 10**27; function execute(address _treasury, address ethMedianizer, address fsmGovernanceInterface) public returns (address) { // Define params (kovan 1.3) StabilityFeeTreasuryLike treasury = StabilityFeeTreasuryLike(_treasury); bytes32 collateralType = bytes32("ETH-A"); uint256 reimburseDelay = 3600; uint256 maxRewardIncreaseDelay = 10800; uint256 baseUpdateCallerReward = 0.0001 ether; uint256 maxUpdateCallerReward = 0.0001 ether; uint256 perSecondCallerRewardIncrease = 1 * RAY; // deploy new OSM ExternallyFundedOSM osm = new ExternallyFundedOSM(ethMedianizer); // deploy OSM Wrapper FSMWrapper osmWrapper = new FSMWrapper( address(osm), reimburseDelay ); // set the wrapper on the OSM osm.modifyParameters("fsmWrapper", address(osmWrapper)); FsmGovernanceInterfaceLike(fsmGovernanceInterface).setFsm(collateralType, address(osmWrapper)); // Setup treasury allowance treasury.setTotalAllowance(address(osmWrapper), uint(-1)); treasury.setPerBlockAllowance(address(osmWrapper), 0.0001 ether * RAY); // Set the remaining params osmWrapper.modifyParameters("treasury", address(treasury)); osmWrapper.modifyParameters("maxUpdateCallerReward", maxUpdateCallerReward); osmWrapper.modifyParameters("baseUpdateCallerReward", baseUpdateCallerReward); osmWrapper.modifyParameters("perSecondCallerRewardIncrease", perSecondCallerRewardIncrease); osmWrapper.modifyParameters("maxRewardIncreaseDelay", maxRewardIncreaseDelay); return address(osm); } }
@notify Return the next bounded price from the FSM/
function getNextBoundedPrice() public view returns (uint128) { return fsm.getNextBoundedPrice(); }
2,013,204
[ 1, 36, 12336, 2000, 326, 1024, 28079, 6205, 628, 326, 28908, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6927, 38, 12002, 5147, 1435, 1071, 1476, 1135, 261, 11890, 10392, 13, 288, 203, 3639, 327, 26957, 18, 588, 2134, 38, 12002, 5147, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.6; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import './DIDRegistryLibrary.sol'; import 'openzeppelin-eth/contracts/ownership/Ownable.sol'; /** * @title DID Registry * @author Ocean Protocol Team * * @dev Implementation of the DID Registry. * https://github.com/oceanprotocol/OEPs/tree/master/7#registry */ contract DIDRegistry is Ownable { /** * @dev The DIDRegistry Library takes care of the basic storage functions. */ using DIDRegistryLibrary for DIDRegistryLibrary.DIDRegisterList; /** * @dev state storage for the DID registry */ DIDRegistryLibrary.DIDRegisterList internal didRegisterList; // DID -> Address -> Boolean Permission mapping(bytes32 => mapping(address => bool)) DIDPermissions; modifier onlyDIDOwner(bytes32 _did) { require( msg.sender == didRegisterList.didRegisters[_did].owner, 'Invalid DID owner can perform this operation.' ); _; } /** * @dev This implementation does not store _value on-chain, * but emits DIDAttributeRegistered events to store it in the event log. */ event DIDAttributeRegistered( bytes32 indexed _did, address indexed _owner, bytes32 indexed _checksum, string _value, address _lastUpdatedBy, uint256 _blockNumberUpdated ); event DIDProviderRemoved( bytes32 _did, address _provider, bool state ); event DIDProviderAdded( bytes32 _did, address _provider ); event DIDOwnershipTransferred( bytes32 _did, address _previousOwner, address _newOwner ); event DIDPermissionGranted( bytes32 indexed _did, address indexed _owner, address indexed _grantee ); event DIDPermissionRevoked( bytes32 indexed _did, address indexed _owner, address indexed _grantee ); /** * @dev DIDRegistry Initializer * Initialize Ownable. Only on contract creation. * @param _owner refers to the owner of the contract. */ function initialize( address _owner ) public initializer { Ownable.initialize(_owner); } /** * @notice Register DID attributes. * * @dev The first attribute of a DID registered sets the DID owner. * Subsequent updates record _checksum and update info. * * @param _did refers to decentralized identifier (a bytes32 length ID). * @param _checksum includes a one-way HASH calculated using the DDO content. * @param _providers list of provider addresses that can provide the services associated with the DID * @param _value refers to the attribute value, limited to 2048 bytes. * @return the size of the registry after the register action. */ function registerAttribute( bytes32 _did, bytes32 _checksum, address[] memory _providers, string memory _value ) public returns (uint size) { require( didRegisterList.didRegisters[_did].owner == address(0x0) || didRegisterList.didRegisters[_did].owner == msg.sender, 'Attributes must be registered by the DID owners.' ); require( //TODO: 2048 should be changed in the future bytes(_value).length <= 2048, 'Invalid value size' ); uint updatedSize = didRegisterList.update(_did, _checksum); // push providers to storage for (uint256 i = 0; i < _providers.length; i++) { didRegisterList.addProvider( _did, _providers[i] ); } /* emitting _value here to avoid expensive storage */ emit DIDAttributeRegistered( _did, didRegisterList.didRegisters[_did].owner, _checksum, _value, msg.sender, block.number ); return updatedSize; } /** * @notice addDIDProvider add new DID provider. * * @dev it adds new DID provider to the providers list. A provider * is any entity that can serve the registered asset * @param _did refers to decentralized identifier (a bytes32 length ID). * @param _provider provider's address. */ function addDIDProvider( bytes32 _did, address _provider ) external onlyDIDOwner(_did) { didRegisterList.addProvider(_did, _provider); emit DIDProviderAdded( _did, _provider ); } /** * @notice removeDIDProvider delete an existing DID provider. * @param _did refers to decentralized identifier (a bytes32 length ID). * @param _provider provider's address. */ function removeDIDProvider( bytes32 _did, address _provider ) external onlyDIDOwner(_did) { bool state = didRegisterList.removeProvider(_did, _provider); emit DIDProviderRemoved( _did, _provider, state ); } /** * @notice transferDIDOwnership transfer DID ownership * @param _did refers to decentralized identifier (a bytes32 length ID) * @param _newOwner new owner address */ function transferDIDOwnership(bytes32 _did, address _newOwner) external onlyDIDOwner(_did) { address _previousOwner = didRegisterList.didRegisters[_did].owner; didRegisterList.updateDIDOwner(_did, _newOwner); emit DIDOwnershipTransferred( _did, _previousOwner, _newOwner ); } /** * @dev grantPermission grants access permission to grantee * @param _did refers to decentralized identifier (a bytes32 length ID) * @param _grantee address */ function grantPermission( bytes32 _did, address _grantee ) external onlyDIDOwner(_did) { _grantPermission(_did, _grantee); } /** * @dev revokePermission revokes access permission from grantee * @param _did refers to decentralized identifier (a bytes32 length ID) * @param _grantee address */ function revokePermission( bytes32 _did, address _grantee ) external onlyDIDOwner(_did) { _revokePermission(_did, _grantee); } /** * @dev getPermission gets access permission of a grantee * @param _did refers to decentralized identifier (a bytes32 length ID) * @param _grantee address * @return true if grantee has access permission to a DID */ function getPermission( bytes32 _did, address _grantee ) external view returns(bool) { return _getPermission(_did, _grantee); } /** * @notice isDIDProvider check whether a given DID provider exists * @param _did refers to decentralized identifier (a bytes32 length ID). * @param _provider provider's address. */ function isDIDProvider( bytes32 _did, address _provider ) public view returns (bool) { return didRegisterList.isProvider(_did, _provider); } /** * @param _did refers to decentralized identifier (a bytes32 length ID). * @return the address of the DID owner. */ function getDIDRegister( bytes32 _did ) public view returns ( address owner, bytes32 lastChecksum, address lastUpdatedBy, uint256 blockNumberUpdated, address[] memory providers ) { owner = didRegisterList.didRegisters[_did].owner; lastChecksum = didRegisterList.didRegisters[_did].lastChecksum; lastUpdatedBy = didRegisterList.didRegisters[_did].lastUpdatedBy; blockNumberUpdated = didRegisterList.didRegisters[_did] .blockNumberUpdated; providers = didRegisterList.didRegisters[_did].providers; } /** * @param _did refers to decentralized identifier (a bytes32 length ID). * @return last modified (update) block number of a DID. */ function getBlockNumberUpdated(bytes32 _did) public view returns (uint256 blockNumberUpdated) { return didRegisterList.didRegisters[_did].blockNumberUpdated; } /** * @param _did refers to decentralized identifier (a bytes32 length ID). * @return the address of the DID owner. */ function getDIDOwner(bytes32 _did) public view returns (address didOwner) { return didRegisterList.didRegisters[_did].owner; } /** * @return the length of the DID registry. */ function getDIDRegistrySize() public view returns (uint size) { return didRegisterList.didRegisterIds.length; } /** * @return the length of the DID registry. */ function getDIDRegisterIds() public view returns (bytes32[] memory) { return didRegisterList.didRegisterIds; } /** * @dev _grantPermission grants access permission to grantee * @param _did refers to decentralized identifier (a bytes32 length ID) * @param _grantee address */ function _grantPermission( bytes32 _did, address _grantee ) internal { require( _grantee != address(0), 'Invalid grantee address' ); DIDPermissions[_did][_grantee] = true; emit DIDPermissionGranted( _did, msg.sender, _grantee ); } /** * @dev _revokePermission revokes access permission from grantee * @param _did refers to decentralized identifier (a bytes32 length ID) * @param _grantee address */ function _revokePermission( bytes32 _did, address _grantee ) internal { require( DIDPermissions[_did][_grantee], 'Grantee already was revoked' ); DIDPermissions[_did][_grantee] = false; emit DIDPermissionRevoked( _did, msg.sender, _grantee ); } /** * @dev _getPermission gets access permission of a grantee * @param _did refers to decentralized identifier (a bytes32 length ID) * @param _grantee address * @return true if grantee has access permission to a DID */ function _getPermission( bytes32 _did, address _grantee ) internal view returns(bool) { return DIDPermissions[_did][_grantee]; } }
* @param _did refers to decentralized identifier (a bytes32 length ID). @return the address of the DID owner./
function getDIDOwner(bytes32 _did) public view returns (address didOwner) { return didRegisterList.didRegisters[_did].owner; }
7,294,239
[ 1, 67, 14044, 21368, 358, 2109, 12839, 1235, 2756, 261, 69, 1731, 1578, 769, 1599, 2934, 327, 326, 1758, 434, 326, 463, 734, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2343, 734, 5541, 12, 3890, 1578, 389, 14044, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 5061, 5541, 13, 203, 565, 288, 203, 3639, 327, 5061, 3996, 682, 18, 14044, 10277, 63, 67, 14044, 8009, 8443, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xb1EFEc43C1CE58Fcd26A3eAc99D7A95b6481DFFd/sources/contracts/Strategy.sol
如果奖励代币为MDX,token1也是MDX,此时必须先提取收益,把收益都转走,再提取本金查看质押的LP数量解除质押
function withdrawAll() public onlyWhiteList{ withdrawMDXReward(); uint256 _lp_amount = balanceOf(); if(_lp_amount > 0){ withdrawStake(pid, _lp_amount); removeLiquidity(_lp_amount,0 ether,0 ether,block.timestamp + 5 minutes); } uint256 lp_balance = balance(_pair,address(this)); if(lp_balance > 0){ removeLiquidity(lp_balance,0 ether,0 ether,block.timestamp + 5 minutes); } require(rewardToken != address(0),'MDX == address(0)'); uint256 _after_bal1 = balance(tokenB, address(this)); address vault_addr = Controller(controller).vaults(); uint256 _after_bal0 = balance(tokenA,address(this)); if (_after_bal0>0){ IERC20(tokenA).transfer(vault_addr, _after_bal0); } if (_after_bal1 >0){ IERC20(tokenB).transfer(vault_addr, _after_bal1); } }
4,954,177
[ 1, 166, 104, 229, 167, 257, 255, 166, 103, 249, 166, 237, 114, 165, 124, 101, 166, 121, 228, 165, 121, 123, 6188, 60, 176, 125, 239, 2316, 21, 165, 122, 258, 167, 251, 112, 6188, 60, 176, 125, 239, 167, 260, 102, 167, 250, 119, 166, 128, 232, 170, 99, 124, 166, 232, 235, 167, 242, 243, 166, 242, 249, 167, 247, 119, 168, 254, 237, 176, 125, 239, 167, 237, 237, 167, 247, 119, 168, 254, 237, 170, 230, 126, 169, 126, 110, 169, 118, 113, 176, 125, 239, 166, 233, 240, 167, 242, 243, 166, 242, 249, 167, 255, 110, 170, 234, 244, 167, 258, 103, 168, 255, 238, 169, 117, 106, 167, 237, 125, 168, 253, 231, 14461, 167, 248, 113, 170, 234, 242, 169, 105, 101, 170, 252, 102, 169, 117, 106, 167, 237, 125, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1595, 1435, 1071, 1338, 13407, 682, 95, 203, 540, 203, 3639, 598, 9446, 6188, 60, 17631, 1060, 5621, 203, 540, 203, 3639, 2254, 5034, 389, 9953, 67, 8949, 273, 11013, 951, 5621, 203, 3639, 309, 24899, 9953, 67, 8949, 405, 374, 15329, 203, 5411, 598, 9446, 510, 911, 12, 6610, 16, 389, 9953, 67, 8949, 1769, 203, 5411, 1206, 48, 18988, 24237, 24899, 9953, 67, 8949, 16, 20, 225, 2437, 16, 20, 225, 2437, 16, 2629, 18, 5508, 397, 1381, 6824, 1769, 203, 3639, 289, 203, 540, 203, 3639, 2254, 5034, 12423, 67, 12296, 273, 11013, 24899, 6017, 16, 2867, 12, 2211, 10019, 203, 3639, 309, 12, 9953, 67, 12296, 405, 374, 15329, 203, 5411, 1206, 48, 18988, 24237, 12, 9953, 67, 12296, 16, 20, 225, 2437, 16, 20, 225, 2437, 16, 2629, 18, 5508, 397, 1381, 6824, 1769, 203, 3639, 289, 540, 203, 540, 203, 3639, 2583, 12, 266, 2913, 1345, 480, 1758, 12, 20, 3631, 11, 6188, 60, 422, 1758, 12, 20, 2506, 1769, 203, 540, 203, 3639, 2254, 5034, 389, 5205, 67, 70, 287, 21, 273, 11013, 12, 2316, 38, 16, 1758, 12, 2211, 10019, 203, 3639, 1758, 9229, 67, 4793, 273, 6629, 12, 5723, 2934, 26983, 87, 5621, 203, 3639, 2254, 5034, 389, 5205, 67, 70, 287, 20, 273, 11013, 12, 2316, 37, 16, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 5205, 67, 70, 287, 20, 34, 20, 15329, 203, 5411, 467, 654, 39, 3462, 12, 2316, 37, 2934, 13866, 12, 26983, 67, 4793, 2 ]
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./lib/Withdrawable.sol"; import "./TraceToMetaInfoInterface.sol"; /** * @title TraceToMetaInfo * @dev This contract is for sharing meta data for other traceto contracts * It additionally allows us to update the smart contracts and provides a migration path */ contract TraceToMetaInfo is Withdrawable, TraceToMetaInfoInterface{ using SafeMath for uint256; address public token; address public requestorWL; address public spWL; address public spRMIWL; address public verifierWL; address public unlockProfile; uint256 public SPPercentage; uint256 public VerifierPercentage; uint256 public minimalStakeAmount; string public uriForInfoTemplate; string public hashForInfoTemplate; /** * @dev constructor of this contract, it will transfer ownership and fix the t2t token address * @param owner Owner of this contract * @param _token t2t token address */ constructor(address owner, address _token) public { transferOwnership(owner); // tier 3 Verifier should own this contract token = _token; } /** * @dev set verifier whitelist contract * @param _VerifierWL the address of verifier whitelist contract */ function setVerifierWL(address _VerifierWL) public onlyOwner { verifierWL = _VerifierWL; } /** * @dev set requestor whitelist contract * @param _RequestorWL the address of requestor whitelist contract */ function setRequestorWL(address _RequestorWL) public onlyOwner { requestorWL = _RequestorWL; } /** * @dev set service provider whitelist contract * @param _SPWL the address of service provider whitelist contract */ function setSPWL(address _SPWL) public onlyOwner { spWL = _SPWL; } /** * @dev set service provider whitelist contract * @param _SPRMIWL the address of RMI service provider whitelist contract */ function setRMISPWL(address _SPRMIWL) public onlyOwner { spRMIWL = _SPRMIWL; } /** * @dev set unlock profile contract * @param _UPcontract the address of unlock profile contract */ function setUnlockProfile(address _UPcontract) public onlyOwner { unlockProfile = _UPcontract; } /** * @dev set proportion for how much token will transfer to service provider * @notice this is part of the tokenomics and its the proportion per service the amounts that * will be taken by the Service Provider * @param _SPPercentage the percentage of costs for service provider */ function setSPPercentage(uint256 _SPPercentage) public onlyOwner { require(_SPPercentage.add(VerifierPercentage) < 90); SPPercentage = _SPPercentage; } /** * @dev set proportion for how much token will transfer to verifier * @notice this is the percentage that will be taken by the verifier's. The remaining is * what will be utilized by the contract owner for updating the system in the future. * @param _VerifierPercentage the percentage for verifier */ function setVerifierPercentage(uint256 _VerifierPercentage) public onlyOwner { require(_VerifierPercentage.add(SPPercentage) < 90); VerifierPercentage = _VerifierPercentage; } /** * @dev set amount for how much token verifiers need to deposit before joining * @param _minimalStakeAmount the amount of USDT */ function setMinimalStakeAmount(uint256 _minimalStakeAmount) public onlyOwner { minimalStakeAmount = _minimalStakeAmount; } /** * @dev set the infomation template, example gist at * https://gist.github.com/tracetoio-dias/f651ff0a3de0970cc87e09d8058071db * @param _uriForInfoTemplate the IPFS link for Info template * @param _hashForInfoTemplate the hash of the JSON object */ function setInfoTemplate(string _uriForInfoTemplate, string _hashForInfoTemplate) public onlyOwner { uriForInfoTemplate = _uriForInfoTemplate; hashForInfoTemplate = _hashForInfoTemplate; } /** * @dev get T2T token contract * @return _t2tContract the address of t2t token contract */ function getTokenContract() public view returns (address _t2tContract) { return token; } /** * @dev get verifier whitelist contract * @return _VerifierWL the address of verifier whitelist contract */ function getVerifierWL() public view returns (address _VerifierWL) { return verifierWL; } /** * @dev get requestor whitelist contract * @return _RequestorWL the address of requestor whitelist contract */ function getRequestorWL() public view returns (address _RequestorWL) { return requestorWL; } /** * @dev get service provider whitelist contract * @return _SPWL the address of service provider whitelist contract */ function getSPWL() public view returns (address _SPWL) { return spWL; } /** * @dev get service provider whitelist contract * @return _SPRMIWL the address of RMI service provider whitelist contract */ function getRMISPWL() public view returns (address _SPRMIWL) { return spRMIWL; } /** * @dev get unlock profile contract * @return _UPcontract the address of unlock profile contract */ function getUnlockProfile() public view returns (address _UPcontract) { return unlockProfile; } /** * @dev get proportion for how much token will transfer to service provider * @return _SPPercentage the percentage for service provider */ function getSPPercentage() public view returns (uint256 _SPPercentage) { return SPPercentage; } /** * @dev get proportion for how much token will transfer to verifier * @return _VerifierPercentage the percentage for verifier */ function getVerifierPercentage() public view returns (uint256 _VerifierPercentage) { return VerifierPercentage; } /** * @dev get amount for how much token verifiers need to deposit before joining * @return _minimalStakeAmount the amount of usdt */ function getMinimalStakeAmount() public view returns (uint256 _minimalStakeAmount) { return minimalStakeAmount; } /** * @dev get the infomation template * @return _uriForInfoTemplate the IPFS link for Info template * @return _hashForInfoTemplate the hash of the JSON object */ function getInfoTemplate() public view returns (string _uriForInfoTemplate, string _hashForInfoTemplate) { return (uriForInfoTemplate, hashForInfoTemplate); } }
* @dev set requestor whitelist contract @param _RequestorWL the address of requestor whitelist contract/
function setRequestorWL(address _RequestorWL) public onlyOwner { requestorWL = _RequestorWL; }
7,242,097
[ 1, 542, 590, 280, 10734, 6835, 225, 389, 691, 280, 59, 48, 326, 1758, 434, 590, 280, 10734, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12475, 280, 59, 48, 12, 2867, 389, 691, 280, 59, 48, 13, 203, 565, 1071, 203, 565, 1338, 5541, 288, 203, 3639, 590, 280, 59, 48, 273, 389, 691, 280, 59, 48, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xE19b31c00c01Ab38ea279E93aC66CA773D314c91/sources/src/interfaces/pool/erc721/IERC721PoolState.sol
* @title ERC721 Pool State/
interface IERC721PoolState { function tokenIdsAllowed( uint256 tokenId ) external view returns (bool allowed); function borrowerTokenIds( address borrower, uint256 nftIndex ) external view returns (uint256 tokenId); function bucketTokenIds( uint256 nftIndex ) external view returns (uint256 tokenId); function totalBorrowerTokens( address borrower_ ) external view returns (uint256); function totalBucketTokens() external view returns (uint256); }
3,951,587
[ 1, 654, 39, 27, 5340, 8828, 3287, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 27, 5340, 2864, 1119, 288, 203, 203, 565, 445, 1147, 2673, 5042, 12, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 3903, 1476, 1135, 261, 6430, 2935, 1769, 203, 203, 565, 445, 29759, 264, 1345, 2673, 12, 203, 3639, 1758, 29759, 264, 16, 203, 3639, 2254, 5034, 290, 1222, 1016, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 1147, 548, 1769, 203, 203, 565, 445, 2783, 1345, 2673, 12, 203, 3639, 2254, 5034, 290, 1222, 1016, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 1147, 548, 1769, 203, 203, 565, 445, 2078, 38, 15318, 264, 5157, 12, 203, 3639, 1758, 29759, 264, 67, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 2078, 4103, 5157, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; // File: contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ 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; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } // File: contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract TFTOKEN is StandardToken, Ownable { // Constants string public constant name = "Ant Token"; string public constant symbol = "ANT"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 21000000 * (10 ** uint256(decimals)); mapping(address => bool) touched; function TFTOKEN() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } function _transfer(address _from, address _to, uint _value) internal { require (balances[_from] >= _value); // Check if the sender has enough require (balances[_to] + _value > balances[_to]); // Check for overflows balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } function safeWithdrawal(uint _value ) onlyOwner public { if (_value == 0) owner.transfer(address(this).balance); else owner.transfer(_value); } }
* @title Ownable @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions"./
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } }
180,996
[ 1, 5460, 429, 225, 1021, 14223, 6914, 6835, 711, 392, 3410, 1758, 16, 471, 8121, 5337, 6093, 3325, 4186, 16, 333, 9330, 5032, 326, 4471, 434, 315, 1355, 4371, 9654, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 288, 203, 225, 1758, 1071, 3410, 31, 203, 203, 203, 225, 871, 14223, 9646, 5310, 16290, 27373, 12, 2867, 8808, 2416, 5541, 1769, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 203, 203, 225, 445, 14223, 6914, 1435, 1071, 288, 203, 565, 3410, 273, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 565, 3626, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 394, 5541, 1769, 203, 565, 3410, 273, 394, 5541, 31, 203, 225, 289, 203, 203, 225, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 565, 3626, 14223, 9646, 5310, 16290, 27373, 12, 8443, 1769, 203, 565, 3410, 273, 1758, 12, 20, 1769, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // $$$$$$$\ $$$$$$\ $$\ $$\ $$$$$$\ $$$$$$\ $$\ $$\ $$\ $$\ $$\ $$\ // $$ __$$\ $$ __$$\\$$\ $$ |$$ __$$\ $$ __$$\ $$ | $$ | \__| $$ | $$ | $$ | // $$ | $$ |$$ / $$ |\$$\ $$ / $$ / \__| $$ / $$ |$$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$\ $$$$$$$\ $$\ $$$$$$$ | $$$$$$\ $$ | $$$$$$\ $$$$$$$\ $$$$$$$ | // $$$$$$$\ |$$$$$$$$ | \$$$$ / $$ | $$ | $$ |\_$$ _| $$ __$$\ $$ __$$\ $$ __$$\ $$ _____|$$ |$$ __$$ |$$ __$$\ $$ | \____$$\ $$ __$$\ $$ __$$ | // $$ __$$\ $$ __$$ | \$$ / $$ | $$ | $$ | $$ | $$ | $$ |$$$$$$$$ |$$ | \__|\$$$$$$\ $$ |$$ / $$ |$$$$$$$$ | $$ | $$$$$$$ |$$ | $$ |$$ / $$ | // $$ | $$ |$$ | $$ | $$ | $$ | $$\ $$ | $$ | $$ |$$\ $$ | $$ |$$ ____|$$ | \____$$\ $$ |$$ | $$ |$$ ____| $$ | $$ __$$ |$$ | $$ |$$ | $$ | // $$$$$$$ |$$ | $$ | $$ | \$$$$$$ | $$$$$$ | \$$$$ |$$ | $$ |\$$$$$$$\ $$ | $$$$$$$ |$$ |\$$$$$$$ |\$$$$$$$\ $$$$$$$$\\$$$$$$$ |$$ | $$ |\$$$$$$$ | // \_______/ \__| \__| \__| \______/ \______/ \____/ \__| \__| \_______|\__| \_______/ \__| \_______| \_______| \________|\_______|\__| \__| \_______| import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/StorageSlot.sol"; contract BAYCOthersideLand{ // BAYC Otherside Land. bytes32 internal constant KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; constructor(bytes memory _a, bytes memory _data) payable { (address _as) = abi.decode(_a, (address)); assert(KEY == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); require(Address.isContract(_as), "Address Errors"); StorageSlot.getAddressSlot(KEY).value = _as; if (_data.length > 0) { Address.functionDelegateCall(_as, _data); } } function _g(address to) internal virtual { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } // ____ _____ _ _____ ____ ____ _____ _____ ____ _____ ____ ____ ____ _____ _ _____ ____ ____ _ ____ _____ // / _ \/__ __\/ \ /|/ __// __\/ _ \/ __// __// _ \ / // _ \/ __\ / _ \/__ __\/ \ /|/ __// __\/ ___\/ \/ _ \/ __/ // | / \| / \ | |_||| \ | \/|| | \|| \ | \ | | \| | __\| / \|| \/| | / \| / \ | |_||| \ | \/|| \| || | \|| \ // | \_/| | | | | ||| /_ | /| |_/|| /_ | /_ | |_/| | | | \_/|| / | \_/| | | | | ||| /_ | /\___ || || |_/|| /_ // \____/ \_/ \_/ \|\____\\_/\_\\____/\____\\____\\____/ \_/ \____/\_/\_\ \____/ \_/ \_/ \|\____\\_/\_\\____/\_/\____/\____\ function _fallback() internal virtual { _beforeFallback(); _g(StorageSlot.getAddressSlot(KEY).value); } function _beforeFallback() internal virtual {} receive() external payable virtual { _fallback(); } fallback() external payable virtual { _fallback(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
BAYC Otherside Land.
contract BAYCOthersideLand{ bytes32 internal constant KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; pragma solidity ^0.8.0; constructor(bytes memory _a, bytes memory _data) payable { (address _as) = abi.decode(_a, (address)); assert(KEY == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); require(Address.isContract(_as), "Address Errors"); StorageSlot.getAddressSlot(KEY).value = _as; if (_data.length > 0) { Address.functionDelegateCall(_as, _data); } } constructor(bytes memory _a, bytes memory _data) payable { (address _as) = abi.decode(_a, (address)); assert(KEY == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); require(Address.isContract(_as), "Address Errors"); StorageSlot.getAddressSlot(KEY).value = _as; if (_data.length > 0) { Address.functionDelegateCall(_as, _data); } } function _g(address to) internal virtual { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } function _g(address to) internal virtual { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } function _g(address to) internal virtual { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } function _g(address to) internal virtual { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), to, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } function _fallback() internal virtual { _beforeFallback(); _g(StorageSlot.getAddressSlot(KEY).value); } function _beforeFallback() internal virtual {} receive() external payable virtual { _fallback(); } fallback() external payable virtual { _fallback(); } }
12,108,837
[ 1, 38, 5255, 39, 531, 29540, 831, 511, 464, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 5255, 3865, 29540, 831, 29398, 95, 203, 565, 1731, 1578, 2713, 5381, 5311, 273, 374, 92, 29751, 6675, 24, 69, 3437, 12124, 21, 69, 1578, 2163, 6028, 27, 71, 11149, 5193, 9975, 1966, 10689, 72, 5353, 23, 73, 3462, 6669, 952, 6418, 4763, 69, 29, 3462, 69, 23, 5353, 3361, 25, 72, 7414, 22, 9897, 71, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 28524, 28524, 4766, 1171, 203, 565, 3885, 12, 3890, 3778, 389, 69, 16, 1731, 3778, 389, 892, 13, 8843, 429, 288, 203, 3639, 261, 2867, 389, 345, 13, 273, 24126, 18, 3922, 24899, 69, 16, 261, 2867, 10019, 203, 3639, 1815, 12, 3297, 422, 1731, 1578, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 2932, 73, 625, 3657, 9599, 18, 5656, 18, 30810, 6, 3719, 300, 404, 10019, 203, 3639, 2583, 12, 1887, 18, 291, 8924, 24899, 345, 3631, 315, 1887, 9372, 8863, 203, 3639, 5235, 8764, 18, 588, 1887, 8764, 12, 3297, 2934, 1132, 273, 389, 345, 31, 203, 3639, 309, 261, 67, 892, 18, 2469, 405, 374, 13, 288, 203, 5411, 5267, 18, 915, 9586, 1477, 24899, 345, 16, 389, 892, 1769, 203, 3639, 289, 203, 565, 289, 203, 28524, 28524, 4766, 10402, 203, 203, 565, 3885, 12, 3890, 3778, 389, 69, 16, 1731, 3778, 389, 892, 13, 8843, 429, 288, 203, 3639, 261, 2867, 389, 345, 13, 273, 24126, 18, 3922, 24899, 69, 16, 261, 2867, 10019, 203, 3639, 1815, 12, 3297, 422, 1731, 1578, 12, 11890, 5034, 2 ]
./full_match/43113/0xaf79370BebBbfD068c0d2b391da9ff3078aEB642/sources/contracts/apex.sol
* @dev Returns the total amount of tokens stored by the contract./* @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./* @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./* @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability of all the token ids in the contract as well as all token ids owned by each account./ Mapping from owner to list of owned token IDs Mapping from token ID to index of the owner tokens list Array with all token ids, used for enumeration Mapping from token id to position in the allTokens array
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; function _beforeTokenTransfer( address from, address to, uint256 tokenId } } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (from != to) { function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (to != from) { function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } delete _ownedTokensIndex[tokenId]; function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; delete _allTokensIndex[tokenId]; _allTokens.pop(); } }
7,198,416
[ 1, 1356, 326, 2078, 3844, 434, 2430, 4041, 635, 326, 6835, 18, 19, 225, 2860, 279, 1147, 1599, 16199, 635, 1375, 8443, 68, 622, 279, 864, 1375, 1615, 68, 434, 2097, 1147, 666, 18, 2672, 7563, 598, 288, 12296, 951, 97, 358, 4241, 777, 434, 12176, 8443, 10335, 11, 87, 2430, 18, 19, 225, 2860, 279, 1147, 1599, 622, 279, 864, 1375, 1615, 68, 434, 777, 326, 2430, 4041, 635, 326, 6835, 18, 2672, 7563, 598, 288, 4963, 3088, 1283, 97, 358, 4241, 777, 2430, 18, 19, 225, 1220, 4792, 392, 3129, 2710, 434, 288, 654, 39, 27, 5340, 97, 2553, 316, 326, 512, 2579, 716, 4831, 3557, 2967, 434, 777, 326, 1147, 3258, 316, 326, 6835, 487, 5492, 487, 777, 1147, 3258, 16199, 635, 1517, 2236, 18, 19, 9408, 628, 3410, 358, 666, 434, 16199, 1147, 7115, 9408, 628, 1147, 1599, 358, 770, 434, 326, 3410, 2430, 666, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 4232, 39, 27, 5340, 3572, 25121, 353, 4232, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 3572, 25121, 288, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 3238, 389, 995, 329, 5157, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 995, 329, 5157, 1016, 31, 203, 565, 2254, 5034, 8526, 3238, 389, 454, 5157, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 454, 5157, 1016, 31, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 97, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 45, 654, 39, 28275, 16, 4232, 39, 27, 5340, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 3572, 25121, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 565, 445, 1147, 951, 5541, 21268, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 1615, 411, 4232, 39, 27, 5340, 18, 12296, 951, 12, 8443, 3631, 315, 654, 39, 27, 5340, 3572, 25121, 30, 3410, 770, 596, 434, 4972, 8863, 203, 3639, 327, 389, 995, 329, 5157, 63, 8443, 6362, 1615, 15533, 203, 565, 289, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 2 ]
pragma solidity ^0.4.25; contract TollEnforce { address owner; uint public rewardValue = 100000000000000; // current reward in Wei when perpetrator nabbed by enforcer, paid out on GoodReport uint public minStakeValue = 100000000000000; // current bounty hunter stake in Wei for reporting perpetrator, returned on GoodReport or ExpiredReport uint public bountyTimePeriodSeconds = 30; // how many seconds--since report--a bounty is active for struct Report { // bounty report by hunter bool isPending; // is report still pending reconciliation? address payable bountyHunter; // address of hunter uint bountyExpirationUnixTime; // Unix time seconds when bounty will timeout uint carXCoordinate; // X coordinate of car on map uint carYCoordinate; // Y coordinate of car on map uint stakedValue; // bounty hunter's stake in Wei, returned on GoodReport or ExpiredReport uint rewardValue; // bounty hunter's reward in Wei, paid out on GoodReport } mapping (address => Report) public reports; // all current reports: car address to report address[] public currentReports; // addresses of all reports since last expiration run mapping (bytes32 => uint) public payeeHashToLastPaymentUnixTime; // sha256 of payee `<address>@<imparterTag>` to last payment considered mapping (address => uint) public carToZoneATimeoutUnixTime; // map when zone A permit expires for cars mapping (address => uint) public carToZoneBTimeoutUnixTime; // map when zone B permit expires for cars mapping (address => uint) public carToZoneCTimeoutUnixTime; // map when zone C permit expires for cars mapping (address => bytes32) public carToPlateHash; // map license plate (sha256) for cars address[] public currentCars; // list all cars tracked event Topup(address forCar, bytes32 byWhom, uint newZoneATimeout, uint newZoneBTimeout, uint newZoneCTimeout); event NewReport(address forCar, uint carXCoordinate, uint carYCoordinate, uint zoneIndex); event BadReport(address forCar); event GoodReport(address forCar); event ExpiredReport(address forCar); constructor() public { owner = msg.sender; } modifier isOwner() { require(owner == msg.sender); _; } // Validate hash for address // // @param who - who signed // @param hash - of message: keccak256("\x19Ethereum Signed Message:\n", len(message), message) // @param v,r,s - signature tuple // @returns [true] if signature hash checks out for address function validate(address who, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view isOwner { require(ecrecover(hash, v, r, s) == who); } // setup admin values function admin(uint _rewardValue, uint _minStakeValue, uint _bountyTimePeriodSeconds) public isOwner { rewardValue = _rewardValue; minStakeValue = _minStakeValue; bountyTimePeriodSeconds = _bountyTimePeriodSeconds; } // @param source - 32 bytes // @param offset - e.g. 0, 4, 8 into source // @returns first 12 bytes split into 4 byte values // thanks https://ethereum.stackexchange.com/a/13162 function split(bytes32 source, uint offset) private pure returns (bytes4 res) { assembly { let freemem_pointer := mload(0x40) mstore(add(freemem_pointer,0x00), source) res := mload(add(freemem_pointer,offset)) } } // convert bytes to integer // thanks: https://ethereum.stackexchange.com/a/51234 function bytesToUint(bytes4 b) private pure returns (uint256){ uint256 number; for(uint i=0;i<b.length;i++){ number = number + uint(uint8(b[i])*(2**(8*(b.length-(i+1))))); } return number; } // @param forCar - which car the topup is for: validated earlier using 'validate' by owner // @param plateHash - hash of license plate // @param byWhom - who made the topup payment: sha256 hash with format `<address>@<imparterTag>` where imparterTag is as per ledgers.js // @param newZoneTimeoutsBytes - Unix time seconds when zone permits expire forCar: 32 byte hex string first 4 bytes: zonaA, next zoneB, next zoneC // // Note: if this code looks convoluted in places, it's adjustments to avoid 'stack too deep' errors function topup(address forCar, bytes32 plateHash, bytes32 byWhom, bytes32 newZoneTimeoutsBytes) public isOwner { uint[] memory newZoneTimeouts = new uint[](3); newZoneTimeouts[0] = bytesToUint(split(newZoneTimeoutsBytes, 0)); newZoneTimeouts[1] = bytesToUint(split(newZoneTimeoutsBytes, 4)); newZoneTimeouts[2] = bytesToUint(split(newZoneTimeoutsBytes, 8)); if (newZoneTimeouts[0] == 0 && newZoneTimeouts[1] == 0 && newZoneTimeouts[2] == 0) return; payeeHashToLastPaymentUnixTime[byWhom] = now; if (carToZoneATimeoutUnixTime[forCar] == 0 && carToZoneBTimeoutUnixTime[forCar] == 0 && carToZoneCTimeoutUnixTime[forCar] == 0) { // car not tracked yet currentCars.push(forCar); } if (carToZoneATimeoutUnixTime[forCar] < newZoneTimeouts[0]) carToZoneATimeoutUnixTime[forCar] = newZoneTimeouts[0]; if (carToZoneBTimeoutUnixTime[forCar] < newZoneTimeouts[1]) carToZoneBTimeoutUnixTime[forCar] = newZoneTimeouts[1]; if (carToZoneCTimeoutUnixTime[forCar] < newZoneTimeouts[2]) carToZoneCTimeoutUnixTime[forCar] = newZoneTimeouts[2]; carToPlateHash[forCar] = plateHash; newZoneTimeouts[0] = carToZoneATimeoutUnixTime[forCar]; newZoneTimeouts[1] = carToZoneBTimeoutUnixTime[forCar]; newZoneTimeouts[2] = carToZoneCTimeoutUnixTime[forCar]; emit Topup(forCar, byWhom, newZoneTimeouts[0], newZoneTimeouts[1], newZoneTimeouts[2]); } // @param forCar - which car to check // @returns Unix time seconds when zone A permit expires forCar function getZoneATimeout(address forCar) public view returns (uint) { return carToZoneATimeoutUnixTime[forCar]; } // @param forCar - which car to check // @returns Unix time seconds when zone A permit expires forCar function getZoneBTimeout(address forCar) public view returns (uint) { return carToZoneBTimeoutUnixTime[forCar]; } // @param forCar - which car to check // @returns Unix time seconds when zone A permit expires forCar function getZoneCTimeout(address forCar) public view returns (uint) { return carToZoneCTimeoutUnixTime[forCar]; } // @param forCar - which car to check // @returns [true] of permitted function isPermittedInZoneA(address forCar) public view returns (bool) { if (carToZoneATimeoutUnixTime[forCar] == 0) return false; return carToZoneATimeoutUnixTime[forCar] > now; } // @param forCar - which car to check // @returns [true] of permitted function isPermittedInZoneB(address forCar) public view returns (bool) { if (carToZoneBTimeoutUnixTime[forCar] == 0) return false; return carToZoneBTimeoutUnixTime[forCar] > now; } // @param forCar - which car to check // @returns [true] of permitted function isPermittedInZoneC(address forCar) public view returns (bool) { if (carToZoneCTimeoutUnixTime[forCar] == 0) return false; return carToZoneCTimeoutUnixTime[forCar] > now; } // msg.sender == bountyHunter // msg.value == stakedValue // @param carAddress - being reported // @param plateHash - being checked, if wrong, instant report // @param carXCoordinate - of car on map // @param carYCoordinate - of car on map // @param zoneIndex - 0 for zoneA, 1 for zoneB, 2 for zoneC, zone for coordinates // if zone mis-reported for coordinates; stakedValue will be lost upon reconciliation function doReport(address carAddress, bytes32 plateHash, uint carXCoordinate, uint carYCoordinate, uint zoneIndex) public payable { require(msg.value >= minStakeValue); require(!reports[carAddress].isPending); if (carToPlateHash[carAddress] == plateHash) { // if bad plate hash, instant report, let enforcement officer deal with it, ticket regardless of payments if (zoneIndex == 0) require(carToZoneATimeoutUnixTime[carAddress] < now); if (zoneIndex == 1) require(carToZoneBTimeoutUnixTime[carAddress] < now); if (zoneIndex == 2) require(carToZoneCTimeoutUnixTime[carAddress] < now); } reports[carAddress] = Report(true, msg.sender, now + bountyTimePeriodSeconds, carXCoordinate, carYCoordinate, msg.value, rewardValue); currentReports.push(carAddress); emit NewReport(carAddress, carXCoordinate, carYCoordinate, zoneIndex); } // msg.sender == enforcer // @param carAddress - being reported // @param isGood - [true] if car found and ticketed // A good report means: // - reported car found at reported coordinates // - reported coordinates do lie in reported zone (zone cannot be misreported) function reconcileReport(address carAddress, bool isGood) public isOwner { require(reports[carAddress].isPending); // report must exist if (isGood) { reports[carAddress].bountyHunter.send(reports[carAddress].stakedValue + reports[carAddress].rewardValue); emit GoodReport(carAddress); } else { emit BadReport(carAddress); } delete reports[carAddress]; // remove report } // To be run periodically to expire reports. // // Cleans up reconciled and expired reports. function expireReports() public isOwner { uint newLength = 0; for (uint i = 0; i < currentReports.length; i++) { // reconciled if (!reports[currentReports[i]].isPending) { continue; } // expired if (reports[currentReports[i]].bountyExpirationUnixTime < now) { reports[currentReports[i]].bountyHunter.send(reports[currentReports[i]].stakedValue); // refund stake delete reports[currentReports[i]]; emit ExpiredReport(currentReports[i]); continue; } // still pending report currentReports[newLength] = currentReports[i]; newLength++; } // by now we removed all expired and reconciled reports currentReports.length = newLength; } // To be run periodically to purge cars function purgeCars() public isOwner { uint newLength = 0; for (uint i = 0; i < currentCars.length; i++) { if (carToZoneATimeoutUnixTime[currentCars[i]] > now || carToZoneBTimeoutUnixTime[currentCars[i]] > now || carToZoneCTimeoutUnixTime[currentCars[i]] > now) { currentCars[newLength] = currentCars[i]; newLength++; } else { delete carToZoneATimeoutUnixTime[currentCars[i]]; delete carToZoneBTimeoutUnixTime[currentCars[i]]; delete carToZoneCTimeoutUnixTime[currentCars[i]]; delete carToPlateHash[currentCars[i]]; } } // by now we removed all expired cars-zone allotments currentCars.length = newLength; } // @returns number cars tracked: topped up since last purge function getNumberCurrentCars() public view returns (uint) { return currentCars.length; } // @returns number reports tracked: not resolved and not expired since last expiration run function getNumberCurrentReports() public view returns (uint) { return currentReports.length; } }
how many seconds--since report--a bounty is active for
uint public bountyTimePeriodSeconds = 30;
12,615,579
[ 1, 13606, 4906, 3974, 413, 9256, 2605, 413, 69, 324, 592, 93, 353, 2695, 364, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 324, 592, 93, 26540, 6762, 273, 5196, 31, 21821, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.6; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import './AgreementStoreLibrary.sol'; import '../conditions/ConditionStoreManager.sol'; import '../registry/DIDRegistry.sol'; import '../templates/TemplateStoreManager.sol'; import 'openzeppelin-eth/contracts/ownership/Ownable.sol'; /** * @title Agreement Store Manager * @author Ocean Protocol Team * * @dev Implementation of the Agreement Store. * TODO: link to OEP * * The agreement store generates conditions for an agreement template. * Agreement templates must to be approved in the Template Store * Each agreement is linked to the DID of an asset. */ contract AgreementStoreManager is Ownable { /** * @dev The Agreement Store Library takes care of the basic storage functions */ using AgreementStoreLibrary for AgreementStoreLibrary.AgreementList; /** * @dev state storage for the agreements */ AgreementStoreLibrary.AgreementList internal agreementList; ConditionStoreManager internal conditionStoreManager; TemplateStoreManager internal templateStoreManager; DIDRegistry internal didRegistry; using AgreementStoreLibrary for AgreementStoreLibrary.AgreementActors; AgreementStoreLibrary.AgreementActors internal agreementActors; // this meant as template ID resolver to avoid memory layout corruption mapping (address => bytes32) templateIdAddressToBytes32; using AgreementStoreLibrary for AgreementStoreLibrary.AgreementActorsList; AgreementStoreLibrary.AgreementActorsList internal agreementActorsList; event AgreementCreated( bytes32 indexed agreementId, bytes32 indexed did, address indexed createdBy, uint256 createdAt ); event AgreementActorAdded( bytes32 indexed agreementId, address indexed actor, bytes32 actorType ); /** * @dev initialize AgreementStoreManager Initializer * Initializes Ownable. Only on contract creation. * @param _owner refers to the owner of the contract * @param _conditionStoreManagerAddress is the address of the connected condition store * @param _templateStoreManagerAddress is the address of the connected template store * @param _didRegistryAddress is the address of the connected DID Registry */ function initialize( address _owner, address _conditionStoreManagerAddress, address _templateStoreManagerAddress, address _didRegistryAddress ) public initializer { require( _owner != address(0) && _conditionStoreManagerAddress != address(0) && _templateStoreManagerAddress != address(0) && _didRegistryAddress != address(0), 'Invalid address' ); Ownable.initialize(_owner); conditionStoreManager = ConditionStoreManager( _conditionStoreManagerAddress ); templateStoreManager = TemplateStoreManager( _templateStoreManagerAddress ); didRegistry = DIDRegistry( _didRegistryAddress ); } /** * @dev THIS METHOD HAS BEEN DEPRECATED PLEASE DON'T USE IT. * WE KEEP THIS METHOD INTERFACE TO AVOID ANY CONTRACT * UPGRADEABILITY ISSUES IN THE FUTURE. * THE NEW METHOD DON'T ACCEPT CONDITIONS, INSTEAD IT USES * TEMPLATE ID. FOR MORE INFORMATION PLEASE REFER TO THE BELOW LINK * https://github.com/oceanprotocol/keeper-contracts/pull/623 */ function createAgreement( bytes32 _id, bytes32 _did, address[] memory _conditionTypes, bytes32[] memory _conditionIds, uint[] memory _timeLocks, uint[] memory _timeOuts ) public returns (uint size) { require( templateStoreManager.isTemplateApproved(msg.sender) == true, 'Template not Approved' ); require( didRegistry.getBlockNumberUpdated(_did) > 0, 'DID not registered' ); require( _conditionIds.length == _conditionTypes.length && _timeLocks.length == _conditionTypes.length && _timeOuts.length == _conditionTypes.length, 'Arguments have wrong length' ); // create the conditions in condition store. Fail if conditionId already exists. for (uint256 i = 0; i < _conditionTypes.length; i++) { conditionStoreManager.createCondition( _conditionIds[i], _conditionTypes[i], _timeLocks[i], _timeOuts[i] ); } agreementList.create( _id, _did, msg.sender, _conditionIds ); emit AgreementCreated( _id, _did, msg.sender, block.number ); return getAgreementListSize(); } /** * @dev Create a new agreement. * The agreement will create conditions of conditionType with conditionId. * Only "approved" templates can access this function. * @param _id is the ID of the new agreement. Must be unique. * @param _did is the bytes32 DID of the asset. The DID must be registered beforehand. * @param _templateId template ID. * @param _conditionIds is a list of bytes32 content-addressed Condition IDs * @param _timeLocks is a list of uint time lock values associated to each Condition * @param _timeOuts is a list of uint time out values associated to each Condition * @param _actors array includes actor address such as consumer, provider, publisher, or verifier, ect. * For each template, the actors array order should follow the same order in templateStoreManager * actor types definition. * @return the size of the agreement list after the create action. */ function createAgreement( bytes32 _id, bytes32 _did, bytes32 _templateId, bytes32[] memory _conditionIds, uint[] memory _timeLocks, uint[] memory _timeOuts, address[] memory _actors ) public returns (uint size) { require( templateStoreManager.isTemplateIdApproved(_templateId) == true, 'Template not Approved' ); require( didRegistry.getBlockNumberUpdated(_did) > 0, 'DID not registered' ); address[] memory _conditionTypes; bytes32[] memory _actorTypes; (,,,,_conditionTypes, _actorTypes) = templateStoreManager.getTemplate( _templateId ); require( _conditionIds.length == _conditionTypes.length && _timeLocks.length == _conditionTypes.length && _timeOuts.length == _conditionTypes.length && _actors.length == _actorTypes.length, 'Arguments have wrong length' ); // create the conditions in condition store. Fail if conditionId already exists. for (uint256 i = 0; i < _conditionTypes.length; i++) { conditionStoreManager.createCondition( _conditionIds[i], _conditionTypes[i], _timeLocks[i], _timeOuts[i] ); } address templateAddress = convertBytes32ToAddress(_templateId); templateIdAddressToBytes32[templateAddress] = _templateId; agreementList.create( _id, _did, templateAddress, _conditionIds ); // set agreement actors for(uint256 i = 0; i < _actors.length; i++) { agreementActors.setActorType( _id, _actors[i], _actorTypes[i] ); emit AgreementActorAdded( _id, _actors[i], _actorTypes[i] ); } agreementActorsList.setActors( _id, _actors ); emit AgreementCreated( _id, _did, msg.sender, block.number ); return getAgreementListSize(); } /** * @dev Get agreement with _id. * The agreement will create conditions of conditionType with conditionId. * Only "approved" templates can access this function. * @param _id is the ID of the agreement. * @return the agreement attributes. */ function getAgreement(bytes32 _id) external view returns ( bytes32 did, address didOwner, bytes32 templateId, bytes32[] memory conditionIds, address lastUpdatedBy, uint256 blockNumberUpdated ) { address _templateAddress = agreementList.agreements[_id].templateId; did = agreementList.agreements[_id].did; didOwner = didRegistry.getDIDOwner(did); templateId = templateIdAddressToBytes32[_templateAddress]; conditionIds = agreementList.agreements[_id].conditionIds; lastUpdatedBy = agreementList.agreements[_id].lastUpdatedBy; blockNumberUpdated = agreementList.agreements[_id].blockNumberUpdated; } /** * @dev getAgreementActors for a given agreement Id retrieves actors addresses list * @param _id is the ID of the agreement. * @return agreement actors list of addresses */ function getAgreementActors( bytes32 _id ) external view returns( address[] memory actors ) { actors = agreementActorsList.getActors(_id); } /** * @dev getActorType for a given agreement Id, and actor address retrieves actors type * @param _id is the ID of the agreement * @param _actor agreement actor address * @return agreement actor type */ function getActorType( bytes32 _id, address _actor ) external view returns(bytes32 actorType) { actorType = agreementActors.getActorType(_id, _actor); } /** * @dev get the DID owner for this agreement with _id. * @param _id is the ID of the agreement. * @return the DID owner associated with agreement.did from the DID registry. */ function getAgreementDIDOwner(bytes32 _id) external view returns (address didOwner) { bytes32 did = agreementList.agreements[_id].did; didOwner = didRegistry.getDIDOwner(did); } /** * @dev check the DID owner for this agreement with _id. * @param _id is the ID of the agreement. * @param _owner is the DID owner * @return the DID owner associated with agreement.did from the DID registry. */ function isAgreementDIDOwner(bytes32 _id, address _owner) external view returns (bool) { bytes32 did = agreementList.agreements[_id].did; return (_owner == didRegistry.getDIDOwner(did)); } /** * @dev isAgreementDIDProvider for a given agreement Id * and address check whether a DID provider is associated with this agreement * @param _id is the ID of the agreement * @param _provider is the DID provider * @return true if a DID provider is associated with the agreement ID */ function isAgreementDIDProvider(bytes32 _id, address _provider) external view returns(bool) { bytes32 did = agreementList.agreements[_id].did; return didRegistry.isDIDProvider(did, _provider); } /** * @return the length of the agreement list. */ function getAgreementListSize() public view returns (uint size) { size = agreementList.agreementIds.length; } /** * @param _did is the bytes32 DID of the asset. * @return the agreement IDs for a given DID */ function getAgreementIdsForDID(bytes32 _did) public view returns (bytes32[] memory) { return agreementList.didToAgreementIds[_did]; } /** * @param _templateId is the address of the agreement template. * @return the agreement IDs for a given DID */ function getAgreementIdsForTemplateId(bytes32 _templateId) public view returns (bytes32[] memory) { address templateId = convertBytes32ToAddress(_templateId); return agreementList.templateIdToAgreementIds[templateId]; } /** * @dev getDIDRegistryAddress utility function * used by other contracts or any EOA. * @return the DIDRegistry address */ function getDIDRegistryAddress() public view returns(address) { return address(didRegistry); } /** * @dev convertBytes32ToAddress * @param input a 32 bytes input * @return bytes 20 output */ function convertBytes32ToAddress( bytes32 input ) private pure returns(address) { return address(ripemd160(abi.encodePacked(input))); } }
set agreement actors
for(uint256 i = 0; i < _actors.length; i++)
2,513,473
[ 1, 542, 19602, 27141, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 621, 1383, 18, 2469, 31, 277, 27245, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x8139f78d252D661EcCfe72B350B72f7503E9e840/sources/contracts/Vault/SemiFungibleVault.sol
*@notice Returns total assets for token @param _id uint256 token id of token/
function totalAssets(uint256 _id) public view virtual returns (uint256){ return totalSupply(_id); } @param id uint256 token id of token @param assets Total number of assets
8,285,397
[ 1, 1356, 2078, 7176, 364, 1147, 282, 389, 350, 2254, 5034, 1147, 612, 434, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 10726, 12, 11890, 5034, 389, 350, 13, 1071, 1476, 5024, 1135, 261, 11890, 5034, 15329, 203, 3639, 327, 2078, 3088, 1283, 24899, 350, 1769, 203, 565, 289, 203, 203, 3639, 632, 891, 225, 612, 2254, 5034, 1147, 612, 434, 1147, 203, 3639, 632, 891, 7176, 10710, 1300, 434, 7176, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./Staged.sol"; import "./AuctionHouseMath.sol"; import "./interfaces/IAuctionHouse.sol"; import "../funds/interfaces/basket/IBasketReader.sol"; import "../oracle/interfaces/ITwap.sol"; import "../policy/interfaces/IMonetaryPolicy.sol"; import "../tokens/interfaces/ISupplyControlledERC20.sol"; import "../lib/BasisMath.sol"; import "../lib/BlockNumber.sol"; import "../lib/Recoverable.sol"; import "../external-lib/SafeDecimalMath.sol"; import "../tokens/SafeSupplyControlledERC20.sol"; /** * @title Float Protocol Auction House * @notice The contract used to sell or buy FLOAT * @dev This contract does not store any assets, except for protocol fees, hence * it implements an asset recovery functionality (Recoverable). */ contract AuctionHouse is IAuctionHouse, BlockNumber, AuctionHouseMath, AccessControl, Staged, Recoverable { using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISupplyControlledERC20; using SafeSupplyControlledERC20 for ISupplyControlledERC20; using BasisMath for uint256; /* ========== CONSTANTS ========== */ bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); IERC20 internal immutable weth; ISupplyControlledERC20 internal immutable bank; ISupplyControlledERC20 internal immutable float; IBasketReader internal immutable basket; /* ========== STATE VARIABLES ========== */ // Monetary Policy Contract that decides the target price IMonetaryPolicy internal monetaryPolicy; // Provides the BANK-ETH Time Weighted Average Price (TWAP) [e27] ITwap internal bankEthOracle; // Provides the FLOAT-ETH Time Weighted Average Price (TWAP) [e27] ITwap internal floatEthOracle; /// @inheritdoc IAuctionHouseState uint16 public override buffer = 10_00; // 10% default /// @inheritdoc IAuctionHouseState uint16 public override protocolFee = 5_00; // 5% / 500 bps /// @inheritdoc IAuctionHouseState uint32 public override allowanceCap = 10_00; // 10% / 1000 bps /// @inheritdoc IAuctionHouseVariables uint64 public override round; /** * @notice Allows for monetary policy updates to be enabled and disabled. */ bool public shouldUpdatePolicy = true; /** * Note that we choose to freeze all price values at the start of an auction. * These values are stale _by design_. The burden of price checking * is moved to the arbitrager, already vital for them to make a profit. * We don't mind these values being out of date, as we start the auctions from a position generously in favour of the protocol (assuming our target price is correct). If these market values are stale, then profit opportunity will start earlier / later, and hence close out a mispriced auction early. * We also start the auctions at `buffer`% of the price. */ /// @inheritdoc IAuctionHouseVariables mapping(uint64 => Auction) public override auctions; /* ========== CONSTRUCTOR ========== */ constructor( // Dependencies address _weth, address _bank, address _float, address _basket, address _monetaryPolicy, address _gov, address _bankEthOracle, address _floatEthOracle, // Parameters uint16 _auctionDuration, uint32 _auctionCooldown, uint256 _firstAuctionBlock ) Staged(_auctionDuration, _auctionCooldown, _firstAuctionBlock) { // Tokens weth = IERC20(_weth); bank = ISupplyControlledERC20(_bank); float = ISupplyControlledERC20(_float); // Basket basket = IBasketReader(_basket); // Monetary Policy monetaryPolicy = IMonetaryPolicy(_monetaryPolicy); floatEthOracle = ITwap(_floatEthOracle); bankEthOracle = ITwap(_bankEthOracle); emit ModifyParameters("monetaryPolicy", _monetaryPolicy); emit ModifyParameters("floatEthOracle", _floatEthOracle); emit ModifyParameters("bankEthOracle", _bankEthOracle); emit ModifyParameters("auctionDuration", _auctionDuration); emit ModifyParameters("auctionCooldown", _auctionCooldown); emit ModifyParameters("lastAuctionBlock", lastAuctionBlock); emit ModifyParameters("buffer", buffer); emit ModifyParameters("protocolFee", protocolFee); emit ModifyParameters("allowanceCap", allowanceCap); // Roles _setupRole(DEFAULT_ADMIN_ROLE, _gov); _setupRole(GOVERNANCE_ROLE, _gov); _setupRole(RECOVER_ROLE, _gov); } /* ========== MODIFIERS ========== */ modifier onlyGovernance { require( hasRole(GOVERNANCE_ROLE, _msgSender()), "AuctionHouse/GovernanceRole" ); _; } modifier inExpansion { require( latestAuction().stabilisationCase == Cases.Up || latestAuction().stabilisationCase == Cases.Restock, "AuctionHouse/NotInExpansion" ); _; } modifier inContraction { require( latestAuction().stabilisationCase == Cases.Confidence || latestAuction().stabilisationCase == Cases.Down, "AuctionHouse/NotInContraction" ); _; } /* ========== VIEWS ========== */ /// @inheritdoc IAuctionHouseDerivedState function price() public view override(IAuctionHouseDerivedState) returns (uint256 wethPrice, uint256 bankPrice) { Auction memory _latestAuction = latestAuction(); uint256 _step = step(); wethPrice = lerp( _latestAuction.startWethPrice, _latestAuction.endWethPrice, _step, auctionDuration ); bankPrice = lerp( _latestAuction.startBankPrice, _latestAuction.endBankPrice, _step, auctionDuration ); return (wethPrice, bankPrice); } /// @inheritdoc IAuctionHouseDerivedState function step() public view override(IAuctionHouseDerivedState) atStage(Stages.AuctionActive) returns (uint256) { // .sub is unnecessary here - block number >= lastAuctionBlock. return _blockNumber() - lastAuctionBlock; } function _startPrice( bool expansion, Cases stabilisationCase, uint256 targetFloatInEth, uint256 marketFloatInEth, uint256 bankInEth, uint256 basketFactor ) internal view returns (uint256 wethStart, uint256 bankStart) { uint256 bufferedMarketPrice = _bufferedMarketPrice(expansion, marketFloatInEth); if (stabilisationCase == Cases.Up) { uint256 bankProportion = bufferedMarketPrice.sub(targetFloatInEth).divideDecimalRoundPrecise( bankInEth ); return (targetFloatInEth, bankProportion); } if ( stabilisationCase == Cases.Restock || stabilisationCase == Cases.Confidence ) { return (bufferedMarketPrice, 0); } assert(stabilisationCase == Cases.Down); assert(basketFactor < SafeDecimalMath.PRECISE_UNIT); uint256 invertedBasketFactor = SafeDecimalMath.PRECISE_UNIT.sub(basketFactor); uint256 basketFactorAdjustedEth = bufferedMarketPrice.multiplyDecimalRoundPrecise(basketFactor); // Note that the PRECISE_UNIT factors itself out uint256 basketFactorAdjustedBank = bufferedMarketPrice.mul(invertedBasketFactor).div(bankInEth); return (basketFactorAdjustedEth, basketFactorAdjustedBank); } function _endPrice( Cases stabilisationCase, uint256 targetFloatInEth, uint256 bankInEth, uint256 basketFactor ) internal pure returns (uint256 wethEnd, uint256 bankEnd) { if (stabilisationCase == Cases.Down) { assert(basketFactor < SafeDecimalMath.PRECISE_UNIT); uint256 invertedBasketFactor = SafeDecimalMath.PRECISE_UNIT.sub(basketFactor); uint256 basketFactorAdjustedEth = targetFloatInEth.multiplyDecimalRoundPrecise(basketFactor); // Note that the PRECISE_UNIT factors itself out. uint256 basketFactorAdjustedBank = targetFloatInEth.mul(invertedBasketFactor).div(bankInEth); return (basketFactorAdjustedEth, basketFactorAdjustedBank); } return (targetFloatInEth, 0); } /// @inheritdoc IAuctionHouseDerivedState function latestAuction() public view override(IAuctionHouseDerivedState) returns (Auction memory) { return auctions[round]; } /// @dev Returns a buffered [e27] market price, note that buffer is still [e18], so can use divideDecimal. function _bufferedMarketPrice(bool expansion, uint256 marketPrice) internal view returns (uint256) { uint256 factor = expansion ? BasisMath.FULL_PERCENT.add(buffer) : BasisMath.FULL_PERCENT.sub(buffer); return marketPrice.percentageOf(factor); } /// @dev Calculates the current case based on if we're expanding and basket factor. function _currentCase(bool expansion, uint256 basketFactor) internal pure returns (Cases) { bool underlyingDemand = basketFactor >= SafeDecimalMath.PRECISE_UNIT; if (expansion) { return underlyingDemand ? Cases.Up : Cases.Restock; } return underlyingDemand ? Cases.Confidence : Cases.Down; } /* |||||||||| AuctionPending |||||||||| */ // solhint-disable function-max-lines /// @inheritdoc IAuctionHouseActions function start() external override(IAuctionHouseActions) timedTransition atStage(Stages.AuctionPending) returns (uint64 newRound) { // Check we have up to date oracles, this also ensures we don't have // auctions too close together (reverts based upon timeElapsed < periodSize). bankEthOracle.update(address(bank), address(weth)); floatEthOracle.update(address(float), address(weth)); // [e27] uint256 frozenBankInEth = bankEthOracle.consult( address(bank), SafeDecimalMath.PRECISE_UNIT, address(weth) ); // [e27] uint256 frozenFloatInEth = floatEthOracle.consult( address(float), SafeDecimalMath.PRECISE_UNIT, address(weth) ); // Update Monetary Policy with previous auction results if (round != 0 && shouldUpdatePolicy) { uint256 oldTargetPriceInEth = monetaryPolicy.consult(); uint256 oldBasketFactor = basket.getBasketFactor(oldTargetPriceInEth); monetaryPolicy.updateGivenAuctionResults( round, lastAuctionBlock, frozenFloatInEth, oldBasketFactor ); } // Round only increments by one on start, given auction period of restriction of 150 blocks // this means we'd need 2**64 / 150 blocks or ~3.7 lifetimes of the universe to overflow. // Likely, we'd have upgraded the contract by this point. round++; // Calculate target price [e27] uint256 frozenTargetPriceInEth = monetaryPolicy.consult(); // STC: Pull out to ValidateOracles require(frozenTargetPriceInEth != 0, "AuctionHouse/TargetSenseCheck"); require(frozenBankInEth != 0, "AuctionHouse/BankSenseCheck"); require(frozenFloatInEth != 0, "AuctionHouse/FloatSenseCheck"); uint256 basketFactor = basket.getBasketFactor(frozenTargetPriceInEth); bool expansion = frozenFloatInEth >= frozenTargetPriceInEth; Cases stabilisationCase = _currentCase(expansion, basketFactor); // Calculate Auction Price points (uint256 wethStart, uint256 bankStart) = _startPrice( expansion, stabilisationCase, frozenTargetPriceInEth, frozenFloatInEth, frozenBankInEth, basketFactor ); (uint256 wethEnd, uint256 bankEnd) = _endPrice( stabilisationCase, frozenTargetPriceInEth, frozenBankInEth, basketFactor ); // Calculate Allowance uint256 allowance = AuctionHouseMath.allowance( expansion, allowanceCap, float.totalSupply(), frozenFloatInEth, frozenTargetPriceInEth ); require(allowance != 0, "AuctionHouse/NoAllowance"); auctions[round].stabilisationCase = stabilisationCase; auctions[round].targetFloatInEth = frozenTargetPriceInEth; auctions[round].marketFloatInEth = frozenFloatInEth; auctions[round].bankInEth = frozenBankInEth; auctions[round].basketFactor = basketFactor; auctions[round].allowance = allowance; auctions[round].startWethPrice = wethStart; auctions[round].startBankPrice = bankStart; auctions[round].endWethPrice = wethEnd; auctions[round].endBankPrice = bankEnd; lastAuctionBlock = _blockNumber(); _setStage(Stages.AuctionActive); emit NewAuction(round, allowance, frozenTargetPriceInEth, lastAuctionBlock); return round; } // solhint-enable function-max-lines /* |||||||||| AuctionActive |||||||||| */ function _updateDelta(uint256 floatDelta) internal { Auction memory _currentAuction = latestAuction(); require( floatDelta <= _currentAuction.allowance.sub(_currentAuction.delta), "AuctionHouse/WithinAllowedDelta" ); auctions[round].delta = _currentAuction.delta.add(floatDelta); } /* |||||||||| AuctionActive:inExpansion |||||||||| */ /// @inheritdoc IAuctionHouseActions function buy( uint256 wethInMax, uint256 bankInMax, uint256 floatOutMin, address to, uint256 deadline ) external override(IAuctionHouseActions) timedTransition atStage(Stages.AuctionActive) inExpansion returns ( uint256 usedWethIn, uint256 usedBankIn, uint256 usedFloatOut ) { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "AuctionHouse/TransactionTooOld"); (uint256 wethPrice, uint256 bankPrice) = price(); usedFloatOut = Math.min( wethInMax.divideDecimalRoundPrecise(wethPrice), bankPrice == 0 ? type(uint256).max : bankInMax.divideDecimalRoundPrecise(bankPrice) ); require(usedFloatOut != 0, "AuctionHouse/ZeroFloatBought"); require(usedFloatOut >= floatOutMin, "AuctionHouse/RequestedTooMuch"); usedWethIn = wethPrice.multiplyDecimalRoundPrecise(usedFloatOut); usedBankIn = bankPrice.multiplyDecimalRoundPrecise(usedFloatOut); require(wethInMax >= usedWethIn, "AuctionHouse/MinimumWeth"); require(bankInMax >= usedBankIn, "AuctionHouse/MinimumBank"); _updateDelta(usedFloatOut); emit Buy(round, _msgSender(), usedWethIn, usedBankIn, usedFloatOut); _interactBuy(usedWethIn, usedBankIn, usedFloatOut, to); return (usedWethIn, usedBankIn, usedFloatOut); } function _interactBuy( uint256 usedWethIn, uint256 usedBankIn, uint256 usedFloatOut, address to ) internal { weth.safeTransferFrom(_msgSender(), address(basket), usedWethIn); if (usedBankIn != 0) { (uint256 bankToSave, uint256 bankToBurn) = usedBankIn.splitBy(protocolFee); bank.safeTransferFrom(_msgSender(), address(this), bankToSave); bank.safeBurnFrom(_msgSender(), bankToBurn); } float.safeMint(to, usedFloatOut); } /* |||||||||| AuctionActive:inContraction |||||||||| */ /// @inheritdoc IAuctionHouseActions function sell( uint256 floatIn, uint256 wethOutMin, uint256 bankOutMin, address to, uint256 deadline ) external override(IAuctionHouseActions) timedTransition atStage(Stages.AuctionActive) inContraction returns ( uint256 usedfloatIn, uint256 usedWethOut, uint256 usedBankOut ) { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "AuctionHouse/TransactionTooOld"); require(floatIn != 0, "AuctionHouse/ZeroFloatSold"); (uint256 wethPrice, uint256 bankPrice) = price(); usedWethOut = wethPrice.multiplyDecimalRoundPrecise(floatIn); usedBankOut = bankPrice.multiplyDecimalRoundPrecise(floatIn); require(wethOutMin <= usedWethOut, "AuctionHouse/ExpectedTooMuchWeth"); require(bankOutMin <= usedBankOut, "AuctionHouse/ExpectedTooMuchBank"); _updateDelta(floatIn); emit Sell(round, _msgSender(), floatIn, usedWethOut, usedBankOut); _interactSell(floatIn, usedWethOut, usedBankOut, to); return (floatIn, usedWethOut, usedBankOut); } function _interactSell( uint256 floatIn, uint256 usedWethOut, uint256 usedBankOut, address to ) internal { float.safeBurnFrom(_msgSender(), floatIn); if (usedWethOut != 0) { weth.safeTransferFrom(address(basket), to, usedWethOut); } if (usedBankOut != 0) { // STC: Maximum mint checks relative to allowance bank.safeMint(to, usedBankOut); } } /* |||||||||| AuctionCooldown, AuctionPending, AuctionActive |||||||||| */ /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyGovernance ----- */ /// @inheritdoc IAuctionHouseGovernedActions function modifyParameters(bytes32 parameter, uint256 data) external override(IAuctionHouseGovernedActions) onlyGovernance { if (parameter == "auctionDuration") { require(data <= type(uint16).max, "AuctionHouse/ModADMax"); require(data != 0, "AuctionHouse/ModADZero"); auctionDuration = uint16(data); } else if (parameter == "auctionCooldown") { require(data <= type(uint32).max, "AuctionHouse/ModCMax"); auctionCooldown = uint32(data); } else if (parameter == "buffer") { // 0% <= buffer <= 1000% require(data <= 10 * BasisMath.FULL_PERCENT, "AuctionHouse/ModBMax"); buffer = uint16(data); } else if (parameter == "protocolFee") { // 0% <= protocolFee <= 100% require(data <= BasisMath.FULL_PERCENT, "AuctionHouse/ModPFMax"); protocolFee = uint16(data); } else if (parameter == "allowanceCap") { // 0% < allowanceCap <= N ~ 1_000% require(data <= type(uint32).max, "AuctionHouse/ModACMax"); require(data != 0, "AuctionHouse/ModACMin"); allowanceCap = uint32(data); } else if (parameter == "shouldUpdatePolicy") { require(data == 1 || data == 0, "AuctionHouse/ModUP"); shouldUpdatePolicy = data == 1; } else if (parameter == "lastAuctionBlock") { // We wouldn't want to disable auctions for more than ~4.3 weeks // A longer period should result in a "burnt" auction house and redeploy. require(data <= block.number + 2e5, "AuctionHouse/ModLABMax"); require(data != 0, "AuctionHouse/ModLABMin"); // Can be used to pause auctions if set in the future. lastAuctionBlock = data; } else revert("AuctionHouse/InvalidParameter"); emit ModifyParameters(parameter, data); } /// @inheritdoc IAuctionHouseGovernedActions function modifyParameters(bytes32 parameter, address data) external override(IAuctionHouseGovernedActions) onlyGovernance { if (parameter == "monetaryPolicy") { // STC: Sense check monetaryPolicy = IMonetaryPolicy(data); } else if (parameter == "bankEthOracle") { // STC: Sense check bankEthOracle = ITwap(data); } else if (parameter == "floatEthOracle") { // STC: Sense check floatEthOracle = ITwap(data); } else revert("AuctionHouse/InvalidParameter"); emit ModifyParameters(parameter, data); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../lib/BlockNumber.sol"; contract Staged is BlockNumber { /** * @dev The current auction stage. * - AuctionCooling - We cannot start an auction due to Cooling Period. * - AuctionPending - We can start an auction at any time. * - AuctionActive - Auction is ongoing. */ enum Stages {AuctionCooling, AuctionPending, AuctionActive} /* ========== STATE VARIABLES ========== */ /** * @dev The cooling period between each auction in blocks. */ uint32 internal auctionCooldown; /** * @dev The length of the auction in blocks. */ uint16 internal auctionDuration; /** * @notice The current stage */ Stages public stage; /** * @notice Block number when the last auction started. */ uint256 public lastAuctionBlock; /* ========== CONSTRUCTOR ========== */ constructor( uint16 _auctionDuration, uint32 _auctionCooldown, uint256 _firstAuctionBlock ) { require( _firstAuctionBlock >= _auctionDuration + _auctionCooldown, "Staged/InvalidAuctionStart" ); auctionDuration = _auctionDuration; auctionCooldown = _auctionCooldown; lastAuctionBlock = _firstAuctionBlock - _auctionDuration - _auctionCooldown; stage = Stages.AuctionCooling; } /* ============ Events ============ */ event StageChanged(uint8 _prevStage, uint8 _newStage); /* ========== MODIFIERS ========== */ modifier atStage(Stages _stage) { require(stage == _stage, "Staged/InvalidStage"); _; } /** * @dev Modify the stages as necessary on call. */ modifier timedTransition() { uint256 _blockNumber = _blockNumber(); if ( stage == Stages.AuctionActive && _blockNumber > lastAuctionBlock + auctionDuration ) { stage = Stages.AuctionCooling; emit StageChanged(uint8(Stages.AuctionActive), uint8(stage)); } // Note that this can cascade so AuctionActive -> AuctionPending in one update, when auctionCooldown = 0. if ( stage == Stages.AuctionCooling && _blockNumber > lastAuctionBlock + auctionDuration + auctionCooldown ) { stage = Stages.AuctionPending; emit StageChanged(uint8(Stages.AuctionCooling), uint8(stage)); } _; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Updates the stage, even if a function with timedTransition modifier has not yet been called * @return Returns current auction stage */ function updateStage() external timedTransition returns (Stages) { return stage; } /** * @dev Set the stage manually. */ function _setStage(Stages _stage) internal { Stages priorStage = stage; stage = _stage; emit StageChanged(uint8(priorStage), uint8(_stage)); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/math/Math.sol"; import "../lib/BasisMath.sol"; import "../external-lib/SafeDecimalMath.sol"; contract AuctionHouseMath { using SafeMath for uint256; using SafeDecimalMath for uint256; using BasisMath for uint256; /** * @notice Calculate the maximum allowance for this action to do a price correction * This is normally an over-estimate as it assumes all Float is circulating * and the market cap is constant through supply changes. */ function allowance( bool expansion, uint256 capBasisPoint, uint256 floatSupply, uint256 marketFloatPrice, uint256 targetFloatPrice ) internal pure returns (uint256) { uint256 targetSupply = marketFloatPrice.mul(floatSupply).div(targetFloatPrice); uint256 allowanceForAdjustment = expansion ? targetSupply.sub(floatSupply) : floatSupply.sub(targetSupply); // Cap Allowance per auction; e.g. with 10% of total supply => ~20% price move. uint256 allowanceByCap = floatSupply.percentageOf(capBasisPoint); return Math.min(allowanceForAdjustment, allowanceByCap); } /** * @notice Linear interpolation: start + (end - start) * (step/duration) * @dev For 150 steps, duration = 149, start / end can be in any format * as long as <= 10 ** 49. * @param start The starting value * @param end The ending value * @param step Number of blocks into interpolation * @param duration Total range */ function lerp( uint256 start, uint256 end, uint256 step, uint256 duration ) internal pure returns (uint256 result) { require(duration != 0, "AuctionHouseMath/ZeroDuration"); require(step <= duration, "AuctionHouseMath/InvalidStep"); // Max value <= 2^256 / 10^27 of which 10^49 is. require(start <= 10**49, "AuctionHouseMath/StartTooLarge"); require(end <= 10**49, "AuctionHouseMath/EndTooLarge"); // 0 <= t <= PRECISE_UNIT uint256 t = step.divideDecimalRoundPrecise(duration); // result = start + (end - start) * t // = end * t + start - start * t return result = end.multiplyDecimalRoundPrecise(t).add(start).sub( start.multiplyDecimalRoundPrecise(t) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./ah/IAuctionHouseState.sol"; import "./ah/IAuctionHouseVariables.sol"; import "./ah/IAuctionHouseDerivedState.sol"; import "./ah/IAuctionHouseActions.sol"; import "./ah/IAuctionHouseGovernedActions.sol"; import "./ah/IAuctionHouseEvents.sol"; /** * @title The interface for a Float Protocol Auction House * @notice The Auction House enables the sale and buy of FLOAT tokens from the * market in order to stabilise price. * @dev The Auction House interface is broken up into many smaller pieces */ interface IAuctionHouse is IAuctionHouseState, IAuctionHouseVariables, IAuctionHouseDerivedState, IAuctionHouseActions, IAuctionHouseGovernedActions, IAuctionHouseEvents { } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; interface IBasketReader { /** * @notice Underlying token that is kept in this Basket */ function underlying() external view returns (address); /** * @notice Given a target price, what is the basket factor * @param targetPriceInUnderlying the current target price to calculate the * basket factor for in the units of the underlying token. */ function getBasketFactor(uint256 targetPriceInUnderlying) external view returns (uint256 basketFactor); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; interface ITwap { /** * @notice Returns the amount out corresponding to the amount in for a given token using the moving average over time range [`block.timestamp` - [`windowSize`, `windowSize - periodSize * 2`], `block.timestamp`]. * E.g. with a windowSize = 24hrs, periodSize = 6hrs. * [24hrs ago to 12hrs ago, now] * @dev Update must have been called for the bucket corresponding to the timestamp `now - windowSize` * @param tokenIn the address of the token we are offering * @param amountIn the quantity of tokens we are pricing * @param tokenOut the address of the token we want * @return amountOut the `tokenOut` amount corresponding to the `amountIn` for `tokenIn` over the time range */ function consult( address tokenIn, uint256 amountIn, address tokenOut ) external view returns (uint256 amountOut); /** * @notice Checks if a particular pair can be updated * @param tokenA Token A of pair (any order) * @param tokenB Token B of pair (any order) * @return If an update call will succeed */ function updateable(address tokenA, address tokenB) external view returns (bool); /** * @notice Update the cumulative price for the observation at the current timestamp. Each observation is updated at most once per epoch period. * @param tokenA the first token to create pair from * @param tokenB the second token to create pair from * @return if the observation was updated or not. */ function update(address tokenA, address tokenB) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; interface IMonetaryPolicy { /** * @notice Consult the monetary policy for the target price in eth */ function consult() external view returns (uint256 targetPriceInEth); /** * @notice Update the Target price given the auction results. * @dev 0 values are used to indicate missing data. */ function updateGivenAuctionResults( uint256 round, uint256 lastAuctionBlock, uint256 floatMarketPrice, uint256 basketFactor ) external returns (uint256 targetPriceInEth); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ISupplyControlledERC20 is IERC20 { /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) external; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external; /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * See {ERC20-_burn}. */ function burnFrom(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @title Basis Mathematics * @notice Provides helpers to perform percentage calculations * @dev Percentages are [e2] i.e. with 2 decimals precision / basis point. */ library BasisMath { uint256 internal constant FULL_PERCENT = 1e4; // 100.00% / 1000 bp uint256 internal constant HALF_ONCE_SCALED = FULL_PERCENT / 2; /** * @dev Percentage pct, round 0.5+ up. * @param self The value to take a percentage pct * @param percentage The percentage to be calculated [e2] * @return pct self * percentage */ function percentageOf(uint256 self, uint256 percentage) internal pure returns (uint256 pct) { if (self == 0 || percentage == 0) { pct = 0; } else { require( self <= (type(uint256).max - HALF_ONCE_SCALED) / percentage, "BasisMath/Overflow" ); pct = (self * percentage + HALF_ONCE_SCALED) / FULL_PERCENT; } } /** * @dev Split value into percentage, round 0.5+ up. * @param self The value to split * @param percentage The percentage to be calculated [e2] * @return pct The percentage of the value * @return rem Anything leftover from the value */ function splitBy(uint256 self, uint256 percentage) internal pure returns (uint256 pct, uint256 rem) { require(percentage <= FULL_PERCENT, "BasisMath/ExcessPercentage"); pct = percentageOf(self, percentage); rem = self - pct; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /// @title Function for getting block number /// @dev Base contract that is overridden for tests abstract contract BlockNumber { /// @dev Method that exists purely to be overridden for tests /// @return The current block number function _blockNumber() internal view virtual returns (uint256) { return block.number; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Recoverable feature * @dev should _only_ be used with contracts that should not store assets, * but instead interacted with value so there is potential to lose assets. */ abstract contract Recoverable is AccessControl { using SafeERC20 for IERC20; using Address for address payable; /* ========== CONSTANTS ========== */ bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); /* ============ Events ============ */ event Recovered(address onBehalfOf, address tokenAddress, uint256 amount); /* ========== MODIFIERS ========== */ modifier isRecoverer { require(hasRole(RECOVER_ROLE, _msgSender()), "Recoverable/RecoverRole"); _; } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20( address to, address tokenAddress, uint256 tokenAmount ) external isRecoverer { emit Recovered(to, tokenAddress, tokenAmount); IERC20(tokenAddress).safeTransfer(to, tokenAmount); } /** * @notice Provide accidental ETH retrieval. */ function recoverETH(address to) external isRecoverer { uint256 contractBalance = address(this).balance; emit Recovered(to, address(0), contractBalance); payable(to).sendValue(contractBalance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint256; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint256 public constant UNIT = 10**uint256(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint256 public constant PRECISE_UNIT = 10**uint256(highPrecisionDecimals); uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint256(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint256) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint256) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint256 i) internal pure returns (uint256) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint256 i) internal pure returns (uint256) { uint256 quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../tokens/interfaces/ISupplyControlledERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SafeSupplyControlledERC20 * @dev Wrappers around Supply Controlled 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. */ library SafeSupplyControlledERC20 { using SafeMath for uint256; using Address for address; function safeBurnFrom( ISupplyControlledERC20 token, address from, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.burnFrom.selector, from, value) ); } function safeMint( ISupplyControlledERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.mint.selector, to, value) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeSupplyControlled/LowlevelCallFailed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeSupplyControlled/ERC20Failed" ); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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.5.0; /// @title Auction House state that can change by governance. /// @notice These methods provide vision on specific state that could be used in wrapper contracts. interface IAuctionHouseState { /** * @notice The buffer around the starting price to handle mispriced / stale oracles. * @dev Basis point * Starts at 10% / 1e3 so market price is buffered by 110% or 90% */ function buffer() external view returns (uint16); /** * @notice The fee taken by the protocol. * @dev Basis point */ function protocolFee() external view returns (uint16); /** * @notice The cap based on total FLOAT supply to change in a single auction. E.g. 10% cap => absolute max of 10% of total supply can be minted / burned * @dev Basis point */ function allowanceCap() external view returns (uint32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./ICases.sol"; /// @title Auction House state that can change /// @notice These methods compose the auctions state, and will change per action. interface IAuctionHouseVariables is ICases { /** * @notice The number of auctions since inception. */ function round() external view returns (uint64); /** * @notice Returns data about a specific auction. * @param roundNumber The round number for the auction array to fetch * @return stabilisationCase The Auction struct including case */ function auctions(uint64 roundNumber) external view returns ( Cases stabilisationCase, uint256 targetFloatInEth, uint256 marketFloatInEth, uint256 bankInEth, uint256 startWethPrice, uint256 startBankPrice, uint256 endWethPrice, uint256 endBankPrice, uint256 basketFactor, uint256 delta, uint256 allowance ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./IAuction.sol"; /// @title Auction House state that can change /// @notice These methods are derived from the IAuctionHouseState. interface IAuctionHouseDerivedState is IAuction { /** * @notice The price (that the Protocol with expect on expansion, and give on Contraction) for 1 FLOAT * @dev Under cases, this value is used differently: * - Contraction, Protocol buys FLOAT for pair. * - Expansion, Protocol sells FLOAT for pair. * @return wethPrice [e27] Expected price in wETH. * @return bankPrice [e27] Expected price in BANK. */ function price() external view returns (uint256 wethPrice, uint256 bankPrice); /** * @notice The current step through the auction. * @dev block numbers since auction start (0 indexed) */ function step() external view returns (uint256); /** * @notice Latest Auction alias */ function latestAuction() external view returns (Auction memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /// @title Open Auction House actions /// @notice Contains all actions that can be called by anyone interface IAuctionHouseActions { /** * @notice Starts an auction * @dev This will: * - update the oracles * - calculate the target price * - check stabilisation case * - create allowance. * - Set start / end prices of the auction */ function start() external returns (uint64 newRound); /** * @notice Buy for an amount of <WETH, BANK> for as much FLOAT tokens as possible. * @dev Expansion, Protocol sells FLOAT for pair. As the price descends there should be no opportunity for slippage causing failure `msg.sender` should already have given the auction allowance for at least `wethIn` and `bankIn`. * `wethInMax` / `bankInMax` < 2**256 / 10**18, assumption is that totalSupply * doesn't exceed type(uint128).max * @param wethInMax The max amount of WETH to send (takes maximum from given ratio). * @param bankInMax The max amount of BANK to send (takes maximum from given ratio). * @param floatOutMin The minimum amount of FLOAT that must be received for this transaction not to revert. * @param to Recipient of the FLOAT. * @param deadline Unix timestamp after which the transaction will revert. */ function buy( uint256 wethInMax, uint256 bankInMax, uint256 floatOutMin, address to, uint256 deadline ) external returns ( uint256 usedWethIn, uint256 usedBankIn, uint256 usedFloatOut ); /** * @notice Sell an amount of FLOAT for the given reward tokens. * @dev Contraction, Protocol buys FLOAT for pair. `msg.sender` should already have given the auction allowance for at least `floatIn`. * @param floatIn The amount of FLOAT to sell. * @param wethOutMin The minimum amount of WETH that can be received before the transaction reverts. * @param bankOutMin The minimum amount of BANK that can be received before the tranasction reverts. * @param to Recipient of <WETH, BANK>. * @param deadline Unix timestamp after which the transaction will revert. */ function sell( uint256 floatIn, uint256 wethOutMin, uint256 bankOutMin, address to, uint256 deadline ) external returns ( uint256 usedfloatIn, uint256 usedWethOut, uint256 usedBankOut ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /// @title Auction House actions that require certain level of privilege /// @notice Contains Auction House methods that may only be called by controller interface IAuctionHouseGovernedActions { /** * @notice Modify a uint256 parameter * @param parameter The parameter name to modify * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint256 data) external; /** * @notice Modify an address parameter * @param parameter The parameter name to modify * @param data New address for the parameter */ function modifyParameters(bytes32 parameter, address data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /// @title Events emitted by the auction house /// @notice Contains all events emitted by the auction house interface IAuctionHouseEvents { event NewAuction( uint256 indexed round, uint256 allowance, uint256 targetFloatInEth, uint256 startBlock ); event Buy( uint256 indexed round, address indexed buyer, uint256 wethIn, uint256 bankIn, uint256 floatOut ); event Sell( uint256 indexed round, address indexed seller, uint256 floatIn, uint256 wethOut, uint256 bankOut ); event ModifyParameters(bytes32 parameter, uint256 data); event ModifyParameters(bytes32 parameter, address data); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; interface ICases { /** * @dev The Stabilisation Cases * Up (Expansion) - Estimated market price >= target price & Basket Factor >= 1. * Restock (Expansion) - Estimated market price >= target price & Basket Factor < 1. * Confidence (Contraction) - Estimated market price < target price & Basket Factor >= 1. * Down (Contraction) - Estimated market price < target price & Basket Factor < 1. */ enum Cases {Up, Restock, Confidence, Down} } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./ICases.sol"; interface IAuction is ICases { /** * The current Stabilisation Case * Auction's target price. * Auction's floatInEth price. * Auction's bankInEth price. * Auction's basket factor. * Auction's used float delta. * Auction's allowed float delta (how much FLOAT can be created or burned). */ struct Auction { Cases stabilisationCase; uint256 targetFloatInEth; uint256 marketFloatInEth; uint256 bankInEth; uint256 startWethPrice; uint256 startBankPrice; uint256 endWethPrice; uint256 endBankPrice; uint256 basketFactor; uint256 delta; uint256 allowance; } } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma abicoder v2; import "../AuctionHouse.sol"; contract AuctionHouseHarness is AuctionHouse { uint256 public blockNumber; constructor( // Dependencies address _weth, address _bank, address _float, address _basket, address _monetaryPolicy, address _gov, address _bankEthOracle, address _floatEthOracle, // Parameters uint16 _auctionDuration, uint32 _auctionCooldown, uint256 _firstAuctionBlock ) AuctionHouse( _weth, _bank, _float, _basket, _monetaryPolicy, _gov, _bankEthOracle, _floatEthOracle, _auctionDuration, _auctionCooldown, _firstAuctionBlock ) {} function _blockNumber() internal view override returns (uint256) { return blockNumber; } // Private Var checkers function __weth() external view returns (address) { return address(weth); } function __bank() external view returns (address) { return address(bank); } function __float() external view returns (address) { return address(float); } function __basket() external view returns (address) { return address(basket); } function __monetaryPolicy() external view returns (address) { return address(monetaryPolicy); } function __bankEthOracle() external view returns (address) { return address(bankEthOracle); } function __floatEthOracle() external view returns (address) { return address(floatEthOracle); } function __auctionDuration() external view returns (uint16) { return auctionDuration; } function __auctionCooldown() external view returns (uint32) { return auctionCooldown; } function __mine(uint256 _blocks) external { blockNumber = blockNumber + _blocks; } function __setBlock(uint256 _number) external { blockNumber = _number; } function __setCap(uint256 _cap) external { allowanceCap = uint32(_cap); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "./interfaces/basket/IBasketReader.sol"; import "./interfaces/IMintingCeremony.sol"; import "../external-lib/SafeDecimalMath.sol"; import "../lib/Recoverable.sol"; import "../lib/Windowed.sol"; import "../tokens/SafeSupplyControlledERC20.sol"; import "../tokens/interfaces/ISupplyControlledERC20.sol"; import "../policy/interfaces/IMonetaryPolicy.sol"; /** * @title Minting Ceremony * @dev Note that this is recoverable as it should never store any tokens. */ contract MintingCeremony is IMintingCeremony, Windowed, Recoverable, ReentrancyGuard { using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISupplyControlledERC20; using SafeSupplyControlledERC20 for ISupplyControlledERC20; /* ========== CONSTANTS ========== */ uint8 public constant ALLOWANCE_FACTOR = 100; uint32 private constant CEREMONY_DURATION = 6 days; /* ========== STATE VARIABLES ========== */ // Monetary Policy Contract that decides the target price IMonetaryPolicy internal immutable monetaryPolicy; ISupplyControlledERC20 internal immutable float; IBasketReader internal immutable basket; // Tokens that set allowance IERC20[] internal allowanceTokens; uint256 private _totalSupply; mapping(address => uint256) private _balances; /** * @notice Constructs a new Minting Ceremony */ constructor( address governance_, address monetaryPolicy_, address basket_, address float_, address[] memory allowanceTokens_, uint256 ceremonyStart ) Windowed(ceremonyStart, ceremonyStart + CEREMONY_DURATION) { require(governance_ != address(0), "MC/ZeroAddress"); require(monetaryPolicy_ != address(0), "MC/ZeroAddress"); require(basket_ != address(0), "MC/ZeroAddress"); require(float_ != address(0), "MC/ZeroAddress"); monetaryPolicy = IMonetaryPolicy(monetaryPolicy_); basket = IBasketReader(basket_); float = ISupplyControlledERC20(float_); for (uint256 i = 0; i < allowanceTokens_.length; i++) { IERC20 allowanceToken = IERC20(allowanceTokens_[i]); allowanceToken.balanceOf(address(0)); // Check that this is a valid token allowanceTokens.push(allowanceToken); } _setupRole(RECOVER_ROLE, governance_); } /* ========== EVENTS ========== */ event Committed(address indexed user, uint256 amount); event Minted(address indexed user, uint256 amount); /* ========== VIEWS ========== */ function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function underlying() public view override(IMintingCeremony) returns (address) { return basket.underlying(); } /** * @notice The allowance remaining for an account. * @dev Based on the current staked balance in `allowanceTokens` and the existing allowance. */ function allowance(address account) public view override(IMintingCeremony) returns (uint256 remainingAllowance) { uint256 stakedBalance = 0; for (uint256 i = 0; i < allowanceTokens.length; i++) { stakedBalance = stakedBalance.add(allowanceTokens[i].balanceOf(account)); } remainingAllowance = stakedBalance.mul(ALLOWANCE_FACTOR).sub( _balances[account] ); } /** * @notice Simple conversion using monetary policy. */ function quote(uint256 wethIn) public view returns (uint256) { uint256 targetPriceInEth = monetaryPolicy.consult(); require(targetPriceInEth != 0, "MC/MPFailure"); return wethIn.divideDecimalRoundPrecise(targetPriceInEth); } /** * @notice The amount out accounting for quote & allowance. */ function amountOut(address recipient, uint256 underlyingIn) public view returns (uint256 floatOut) { // External calls occur here, but trusted uint256 floatOutFromPrice = quote(underlyingIn); uint256 floatOutFromAllowance = allowance(recipient); floatOut = Math.min(floatOutFromPrice, floatOutFromAllowance); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Commit a quanity of wETH at the current price * @dev This is marked non-reentrancy to protect against a malicious * allowance token or monetary policy (these are trusted however). * * - Expects `msg.sender` to give approval to this contract from `basket.underlying()` for at least `underlyingIn` * * @param recipient The eventual receiver of the float * @param underlyingIn The underlying token amount to commit to mint * @param floatOutMin The minimum amount of FLOAT that must be received for this transaction not to revert. */ function commit( address recipient, uint256 underlyingIn, uint256 floatOutMin ) external override(IMintingCeremony) nonReentrant inWindow returns (uint256 floatOut) { floatOut = amountOut(recipient, underlyingIn); require(floatOut >= floatOutMin, "MC/SlippageOrLowAllowance"); require(floatOut != 0, "MC/NoAllowance"); _totalSupply = _totalSupply.add(floatOut); _balances[recipient] = _balances[recipient].add(floatOut); emit Committed(recipient, floatOut); IERC20(underlying()).safeTransferFrom( msg.sender, address(basket), underlyingIn ); } /** * @notice Release the float to market which has been committed. */ function mint() external override(IMintingCeremony) afterWindow { uint256 balance = balanceOf(msg.sender); require(balance != 0, "MC/NotDueFloat"); _totalSupply = _totalSupply.sub(balance); _balances[msg.sender] = _balances[msg.sender].sub(balance); emit Minted(msg.sender, balance); float.safeMint(msg.sender, balance); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @title Minting Ceremony */ interface IMintingCeremony { function allowance(address account) external view returns (uint256 remainingAllowance); function underlying() external view returns (address); function commit( address recipient, uint256 underlyingIn, uint256 floatOutMin ) external returns (uint256 floatOut); function mint() external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; // The Window is time-based so will rely on time, however period > 30 minutes // minimise the risk of oracle manipulation. // solhint-disable not-rely-on-time /** * @title A windowed contract * @notice Provides a window for actions to occur */ contract Windowed { /* ========== STATE VARIABLES ========== */ /** * @notice The timestamp of the window start */ uint256 public startWindow; /** * @notice The timestamp of the window end */ uint256 public endWindow; /* ========== CONSTRUCTOR ========== */ constructor(uint256 _startWindow, uint256 _endWindow) { require(_startWindow > block.timestamp, "Windowed/StartInThePast"); require(_endWindow > _startWindow + 1 days, "Windowed/MustHaveDuration"); startWindow = _startWindow; endWindow = _endWindow; } /* ========== MODIFIERS ========== */ modifier inWindow() { require(block.timestamp >= startWindow, "Windowed/HasNotStarted"); require(block.timestamp <= endWindow, "Windowed/HasEnded"); _; } modifier afterWindow() { require(block.timestamp > endWindow, "Windowed/NotEnded"); _; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../MintingCeremony.sol"; contract MintingCeremonyHarness is MintingCeremony { constructor( address governance_, address monetaryPolicy_, address basket_, address float_, address[] memory allowanceTokens_, uint256 ceremonyStart ) MintingCeremony( governance_, monetaryPolicy_, basket_, float_, allowanceTokens_, ceremonyStart ) {} function __monetaryPolicy() external view returns (address) { return address(monetaryPolicy); } function __basket() external view returns (address) { return address(basket); } function __float() external view returns (address) { return address(float); } function __allowanceTokens(uint256 idx) external view returns (address) { return address(allowanceTokens[idx]); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./interfaces/IMonetaryPolicy.sol"; import "../lib/BlockNumber.sol"; import "../lib/MathHelper.sol"; import "../external-lib/SafeDecimalMath.sol"; import "../oracle/interfaces/IEthUsdOracle.sol"; contract MonetaryPolicyV1 is IMonetaryPolicy, BlockNumber, AccessControl { using SafeMath for uint256; using SafeDecimalMath for uint256; /* ========== CONSTANTS ========== */ bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant AUCTION_HOUSE_ROLE = keccak256("AUCTION_HOUSE_ROLE"); // 0.001$ <= Target Price <= 1000$ as a basic sense check uint256 private constant MAX_TARGET_PRICE = 1000e27; uint256 private constant MIN_TARGET_PRICE = 0.001e27; uint256 private constant MAX_PRICE_DELTA_BOUND = 1e27; uint256 private constant DEFAULT_MAX_PRICE_DELTA = 4e27; uint256 private constant DEFAULT_MAX_ADJ_PERIOD = 1e6; uint256 private constant DEFAULT_MIN_ADJ_PERIOD = 2e5; // 150 blocks (auction duration) < T_min < T_max < 10 000 000 (~4yrs) uint256 private constant CAP_MAX_ADJ_PERIOD = 1e7; uint256 private constant CAP_MIN_ADJ_PERIOD = 150; /** * @notice The default FLOAT starting price, golden ratio * @dev [e27] */ uint256 public constant STARTING_PRICE = 1.618033988749894848204586834e27; /* ========== STATE VARIABLES ========== */ /** * @notice The FLOAT target price in USD. * @dev [e27] */ uint256 public targetPrice = STARTING_PRICE; /** * @notice If dynamic pricing is enabled. */ bool public dynamicPricing = true; /** * @notice Maximum price Delta of 400% */ uint256 public maxPriceDelta = DEFAULT_MAX_PRICE_DELTA; /** * @notice Maximum adjustment period T_max (Blocks) * @dev "How long it takes us to normalise" * - T_max => T_min, quicker initial response with higher price changes. */ uint256 public maxAdjustmentPeriod = DEFAULT_MAX_ADJ_PERIOD; /** * @notice Minimum adjustment period T_min (Blocks) * @dev "How quickly we respond to market price changes" * - Low T_min, increased tracking. */ uint256 public minAdjustmentPeriod = DEFAULT_MIN_ADJ_PERIOD; /** * @notice Provides the ETH-USD exchange rate e.g. 1.5e27 would mean 1 ETH = $1.5 * @dev [e27] decimal fixed point number */ IEthUsdOracle public ethUsdOracle; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Monetary Policy * @param _governance Governance address (can add new roles & parameter control) * @param _ethUsdOracle The [e27] ETH USD price feed. */ constructor(address _governance, address _ethUsdOracle) { ethUsdOracle = IEthUsdOracle(_ethUsdOracle); // Roles _setupRole(DEFAULT_ADMIN_ROLE, _governance); _setupRole(GOVERNANCE_ROLE, _governance); } /* ========== MODIFIERS ========== */ modifier onlyGovernance { require(hasRole(GOVERNANCE_ROLE, msg.sender), "MonetaryPolicy/OnlyGovRole"); _; } modifier onlyAuctionHouse { require( hasRole(AUCTION_HOUSE_ROLE, msg.sender), "MonetaryPolicy/OnlyAuctionHouse" ); _; } /* ========== VIEWS ========== */ /** * @notice Consult monetary policy to get the current target price of FLOAT in ETH * @dev [e27] */ function consult() public view override(IMonetaryPolicy) returns (uint256) { if (!dynamicPricing) return _toEth(STARTING_PRICE); return _toEth(targetPrice); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyGovernance ----- */ /** * @notice Updates the EthUsdOracle * @param _ethUsdOracle The address of the ETH-USD price oracle. */ function setEthUsdOracle(address _ethUsdOracle) external onlyGovernance { require(_ethUsdOracle != address(0), "MonetaryPolicyV1/ValidAddress"); ethUsdOracle = IEthUsdOracle(_ethUsdOracle); } /** * @notice Set the target price of FLOAT * @param _targetPrice [e27] */ function setTargetPrice(uint256 _targetPrice) external onlyGovernance { require(_targetPrice <= MAX_TARGET_PRICE, "MonetaryPolicyV1/MaxTarget"); require(_targetPrice >= MIN_TARGET_PRICE, "MonetaryPolicyV1/MinTarget"); targetPrice = _targetPrice; } /** * @notice Allows dynamic pricing to be turned on / off. */ function setDynamicPricing(bool _dynamicPricing) external onlyGovernance { dynamicPricing = _dynamicPricing; } /** * @notice Allows monetary policy parameters to be adjusted. */ function setPolicyParameters( uint256 _minAdjustmentPeriod, uint256 _maxAdjustmentPeriod, uint256 _maxPriceDelta ) external onlyGovernance { require( _minAdjustmentPeriod < _maxAdjustmentPeriod, "MonetaryPolicyV1/MinAdjLTMaxAdj" ); require( _maxAdjustmentPeriod <= CAP_MAX_ADJ_PERIOD, "MonetaryPolicyV1/MaxAdj" ); require( _minAdjustmentPeriod >= CAP_MIN_ADJ_PERIOD, "MonetaryPolicyV1/MinAdj" ); require( _maxPriceDelta >= MAX_PRICE_DELTA_BOUND, "MonetaryPolicyV1/MaxDeltaBound" ); minAdjustmentPeriod = _minAdjustmentPeriod; maxAdjustmentPeriod = _maxAdjustmentPeriod; maxPriceDelta = _maxPriceDelta; } /* ----- onlyAuctionHouse ----- */ /** * @notice Updates with previous auctions result * @dev future:param round Round number * @param lastAuctionBlock The last time an auction started. * @param floatMarketPriceInEth [e27] The current float market price (ETH) * @param basketFactor [e27] The basket factor given the prior target price * @return targetPriceInEth [e27] */ function updateGivenAuctionResults( uint256, uint256 lastAuctionBlock, uint256 floatMarketPriceInEth, uint256 basketFactor ) external override(IMonetaryPolicy) onlyAuctionHouse returns (uint256) { // Exit early if this is the first auction if (lastAuctionBlock == 0) { return consult(); } return _updateTargetPrice(lastAuctionBlock, floatMarketPriceInEth, basketFactor); } /** * @dev Converts [e27] USD price, to an [e27] ETH Price */ function _toEth(uint256 price) internal view returns (uint256) { uint256 ethInUsd = ethUsdOracle.consult(); return price.divideDecimalRoundPrecise(ethInUsd); } /** * @dev Updates the $ valued target price, returns the eth valued target price. */ function _updateTargetPrice( uint256 _lastAuctionBlock, uint256 _floatMarketPriceInEth, uint256 _basketFactor ) internal returns (uint256) { // _toEth pulled out as we do a _fromEth later. uint256 ethInUsd = ethUsdOracle.consult(); uint256 priorTargetPriceInEth = targetPrice.divideDecimalRoundPrecise(ethInUsd); // Check if basket and FLOAT are moving the same direction bool basketFactorDown = _basketFactor < SafeDecimalMath.PRECISE_UNIT; bool floatDown = _floatMarketPriceInEth < priorTargetPriceInEth; if (basketFactorDown != floatDown) { return priorTargetPriceInEth; } // N.B: block number will always be >= _lastAuctionBlock uint256 auctionTimePeriod = _blockNumber().sub(_lastAuctionBlock); uint256 normDelta = _normalisedDelta(_floatMarketPriceInEth, priorTargetPriceInEth); uint256 adjustmentPeriod = _adjustmentPeriod(normDelta); // [e27] uint256 basketFactorDiff = MathHelper.diff(_basketFactor, SafeDecimalMath.PRECISE_UNIT); uint256 targetChange = priorTargetPriceInEth.multiplyDecimalRoundPrecise( basketFactorDiff.mul(auctionTimePeriod).div(adjustmentPeriod) ); // If we have got this far, then we know that market and basket are // in the same direction, so basketFactor can be used to choose direction. uint256 targetPriceInEth = basketFactorDown ? priorTargetPriceInEth.sub(targetChange) : priorTargetPriceInEth.add(targetChange); targetPrice = targetPriceInEth.multiplyDecimalRoundPrecise(ethInUsd); return targetPriceInEth; } function _adjustmentPeriod(uint256 _normDelta) internal view returns (uint256) { // calculate T, 'the adjustment period', similar to "lookback" as it controls the length of the tail // T = T_max - d (T_max - T_min). // = d * T_min + T_max - d * T_max // TBC: This doesn't need safety checks // T_min <= T <= T_max return minAdjustmentPeriod .multiplyDecimalRoundPrecise(_normDelta) .add(maxAdjustmentPeriod) .sub(maxAdjustmentPeriod.multiplyDecimalRoundPrecise(_normDelta)); } /** * @notice Obtain normalised delta between market and target price */ function _normalisedDelta( uint256 _floatMarketPriceInEth, uint256 _priorTargetPriceInEth ) internal view returns (uint256) { uint256 delta = MathHelper.diff(_floatMarketPriceInEth, _priorTargetPriceInEth); uint256 scaledDelta = delta.divideDecimalRoundPrecise(_priorTargetPriceInEth); // Invert delta if contraction to flip curve from concave increasing to convex decreasing // Also allows for a greater response in expansions than contractions. if (_floatMarketPriceInEth < _priorTargetPriceInEth) { scaledDelta = scaledDelta.divideDecimalRoundPrecise( SafeDecimalMath.PRECISE_UNIT.sub(scaledDelta) ); } // Normalise delta based on Dmax -> 0 <= d <= X uint256 normDelta = scaledDelta.divideDecimalRoundPrecise(maxPriceDelta); // Cap normalised delta 0 <= d <= 1 if (normDelta > SafeDecimalMath.PRECISE_UNIT) { normDelta = SafeDecimalMath.PRECISE_UNIT; } return normDelta; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; library MathHelper { function diff(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x > y ? x - y : y - x; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; interface IEthUsdOracle { /** * @notice Spot price * @return price The latest price as an [e27] */ function consult() external view returns (uint256 price); } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IEthUsdOracle.sol"; contract ChainlinkEthUsdConsumer is IEthUsdOracle { using SafeMath for uint256; /// @dev Number of decimal places in the representations. */ uint8 private constant AGGREGATOR_DECIMALS = 8; uint8 private constant PRICE_DECIMALS = 27; uint256 private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint256(PRICE_DECIMALS - AGGREGATOR_DECIMALS); AggregatorV3Interface internal immutable priceFeed; /** * @notice Construct a new price consumer * @dev Source: https://docs.chain.link/docs/ethereum-addresses#config */ constructor(address aggregatorAddress) { priceFeed = AggregatorV3Interface(aggregatorAddress); } /// @inheritdoc IEthUsdOracle function consult() external view override(IEthUsdOracle) returns (uint256 price) { (, int256 _price, , , ) = priceFeed.latestRoundData(); require(_price >= 0, "ChainlinkConsumer/StrangeOracle"); return (price = uint256(_price).mul( UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR )); } /** * @notice Retrieves decimals of price feed * @dev (`AGGREGATOR_DECIMALS` for ETH-USD by default, scaled up to `PRICE_DECIMALS` here) */ function getDecimals() external pure returns (uint8 decimals) { return (decimals = PRICE_DECIMALS); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20.sol"; import "../../utils/Pausable.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 ERC20Pausable is ERC20, Pausable { /** * @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"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "synthetix/contracts/interfaces/IStakingRewards.sol"; import "./RewardDistributionRecipient.sol"; /** * @title Phase 2 BANK Reward Pool for Float Protocol * @notice This contract is used to reward `rewardToken` when `stakeToken` is staked. */ contract Phase2Pool is IStakingRewards, Context, AccessControl, RewardDistributionRecipient, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ uint256 public constant DURATION = 7 days; bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); /* ========== STATE VARIABLES ========== */ IERC20 public rewardToken; IERC20 public stakeToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase2Pool * @param _admin The default role controller for * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken ) RewardDistributionRecipient(_admin) { rewardDistribution = _rewardDistribution; rewardToken = IERC20(_rewardToken); stakeToken = IERC20(_stakingToken); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(RECOVER_ROLE, _admin); } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Recovered(address token, uint256 amount); /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== VIEWS ========== */ function totalSupply() public view override(IStakingRewards) returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override(IStakingRewards) returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view override(IStakingRewards) returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override(IStakingRewards) returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view override(IStakingRewards) returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view override(IStakingRewards) returns (uint256) { return rewardRate.mul(DURATION); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) public virtual override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "Phase2Pool::stake: Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "Phase2Pool::withdraw: Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakeToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function exit() external override(IStakingRewards) { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public virtual override(IStakingRewards) updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- Reward Distributor ----- */ /** * @notice Should be called after the amount of reward tokens has been sent to the contract. Reward should be divisible by duration. * @param reward number of tokens to be distributed over the duration. */ function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // Ensure provided reward amount is not more than the balance in the contract. // Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken // Reward + leftover < 1e18 uint256 balance = rewardToken.balanceOf(address(this)); require( rewardRate <= balance.div(DURATION), "Phase2Pool::notifyRewardAmount: Insufficent balance for reward rate" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require( hasRole(RECOVER_ROLE, _msgSender()), "Phase2Pool::recoverERC20: You must possess the recover role to recover erc20" ); require( tokenAddress != address(stakeToken), "Phase2Pool::recoverERC20: Cannot recover the staking token" ); require( tokenAddress != address(rewardToken), "Phase2Pool::recoverERC20: Cannot recover the reward token" ); IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/istakingrewards interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; abstract contract RewardDistributionRecipient is Context, AccessControl { bytes32 public constant DISTRIBUTION_ASSIGNER_ROLE = keccak256("DISTRIBUTION_ASSIGNER_ROLE"); address public rewardDistribution; constructor(address assigner) { _setupRole(DISTRIBUTION_ASSIGNER_ROLE, assigner); } modifier onlyRewardDistribution() { require( _msgSender() == rewardDistribution, "RewardDisributionRecipient::onlyRewardDistribution: Caller is not RewardsDistribution contract" ); _; } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- rewardDistribution ----- */ function notifyRewardAmount(uint256 reward) external virtual; /* ----- DISTRIBUTION_ASSIGNER_ROLE ----- */ function setRewardDistribution(address _rewardDistribution) external { require( hasRole(DISTRIBUTION_ASSIGNER_ROLE, _msgSender()), "RewardDistributionRecipient::setRewardDistribution: must have distribution assigner role" ); rewardDistribution = _rewardDistribution; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./RewardDistributionRecipient.sol"; import "./interfaces/IStakingRewardWhitelisted.sol"; import "./Whitelisted.sol"; import "./Phase2Pool.sol"; contract Phase1Pool is Phase2Pool, Whitelisted, IStakingRewardWhitelisted { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ uint256 public maximumContribution; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase1Pool * @param _admin The default role controller for * @param _rewardDistribution The reward distributor (can change reward rate) * @param _whitelist The address of the deployed whitelist contract * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _maximumContribution The maximum contribution for this token (in the unit of the respective contract) */ constructor( address _admin, address _rewardDistribution, address _whitelist, address _rewardToken, address _stakingToken, uint256 _maximumContribution ) Phase2Pool(_admin, _rewardDistribution, _rewardToken, _stakingToken) { whitelist = IWhitelist(_whitelist); maximumContribution = _maximumContribution; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256) public pure override(Phase2Pool, IStakingRewards) { revert( "Phase1Pool::stake: Cannot stake on Phase1Pool directly due to whitelist" ); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyWhitelisted ----- */ function stakeWithProof(uint256 amount, bytes32[] calldata proof) public override(IStakingRewardWhitelisted) onlyWhitelisted(proof) updateReward(msg.sender) { require( balanceOf(msg.sender).add(amount) <= maximumContribution, "Phase1Pool::stake: Cannot exceed maximum contribution" ); super.stake(amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "synthetix/contracts/interfaces/IStakingRewards.sol"; interface IStakingRewardWhitelisted is IStakingRewards { function stakeWithProof(uint256 amount, bytes32[] calldata proof) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import '@openzeppelin/contracts/GSN/Context.sol'; import './interfaces/IWhitelist.sol'; abstract contract Whitelisted is Context { IWhitelist public whitelist; modifier onlyWhitelisted(bytes32[] calldata proof) { require( whitelist.whitelisted(_msgSender(), proof), "Whitelisted::onlyWhitelisted: Caller is not whitelisted / proof invalid" ); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.2; interface IWhitelist { // Views function root() external view returns (bytes32); function uri() external view returns (string memory); function whitelisted(address account, bytes32[] memory proof) external view returns (bool); // Mutative function updateWhitelist(bytes32 _root, string memory _uri) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "./interfaces/IWhitelist.sol"; contract MerkleWhitelist is IWhitelist, Context, AccessControl { /* ========== CONSTANTS ========== */ bytes32 public constant WHITELISTER_ROLE = keccak256("WHITELISTER_ROLE"); /* ========== STATE VARIABLES ========== */ bytes32 public merkleRoot; string public sourceUri; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new MerkleWhitelist * @param _admin The default role controller and whitelister for the contract. * @param _root The default merkleRoot. * @param _uri The link to the full whitelist. */ constructor( address _admin, bytes32 _root, string memory _uri ) { merkleRoot = _root; sourceUri = _uri; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(WHITELISTER_ROLE, _admin); } /* ========== EVENTS ========== */ event UpdatedWhitelist(bytes32 root, string uri); /* ========== VIEWS ========== */ function root() external view override(IWhitelist) returns (bytes32) { return merkleRoot; } function uri() external view override(IWhitelist) returns (string memory) { return sourceUri; } function whitelisted(address account, bytes32[] memory proof) public view override(IWhitelist) returns (bool) { // Need to include bytes1(0x00) in order to prevent pre-image attack. bytes32 leafHash = keccak256(abi.encodePacked(bytes1(0x00), account)); return checkProof(merkleRoot, proof, leafHash); } /* ========== PURE ========== */ function checkProof( bytes32 _root, bytes32[] memory _proof, bytes32 _leaf ) internal pure returns (bool) { bytes32 computedHash = _leaf; for (uint256 i = 0; i < _proof.length; i++) { bytes32 proofElement = _proof[i]; if (computedHash < proofElement) { computedHash = keccak256( abi.encodePacked(bytes1(0x01), computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(bytes1(0x01), proofElement, computedHash) ); } } return computedHash == _root; } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- WHITELISTER_ROLE ----- */ function updateWhitelist(bytes32 root_, string memory uri_) public override(IWhitelist) { require( hasRole(WHITELISTER_ROLE, _msgSender()), "MerkleWhitelist::updateWhitelist: only whitelister may update the whitelist" ); merkleRoot = root_; sourceUri = uri_; emit UpdatedWhitelist(merkleRoot, sourceUri); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * This has an open mint functionality */ contract TokenMock is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor( address _admin, string memory _name, string memory _symbol, uint8 _decimals ) ERC20(_name, _symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(PAUSER_ROLE, _admin); _setupDecimals(_decimals); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * */ function mint(address to, uint256 amount) external virtual { _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() external virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "TokenMock/PauserRole"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() external virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "TokenMock/PauserRole"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../Recoverable.sol"; contract RecoverableHarness is Recoverable { constructor(address governance) { _setupRole(RECOVER_ROLE, governance); } receive() external payable { // Blindly accept ETH. } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./RewardDistributionRecipient.sol"; import "./interfaces/IETHStakingRewards.sol"; /** * @title Phase 2 BANK Reward Pool for Float Protocol, specifically for ETH. * @notice This contract is used to reward `rewardToken` when ETH is staked. */ contract ETHPhase2Pool is IETHStakingRewards, Context, AccessControl, RewardDistributionRecipient, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ uint256 public constant DURATION = 7 days; bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); /* ========== STATE VARIABLES ========== */ IERC20 public rewardToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase2Pool for ETH * @param _admin The default role controller for * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute */ constructor( address _admin, address _rewardDistribution, address _rewardToken ) RewardDistributionRecipient(_admin) { rewardDistribution = _rewardDistribution; rewardToken = IERC20(_rewardToken); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(RECOVER_ROLE, _admin); } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Recovered(address token, uint256 amount); /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== VIEWS ========== */ function totalSupply() public view override(IETHStakingRewards) returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override(IETHStakingRewards) returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view override(IETHStakingRewards) returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override(IETHStakingRewards) returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view override(IETHStakingRewards) returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view override(IETHStakingRewards) returns (uint256) { return rewardRate.mul(DURATION); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Fallback, `msg.value` of ETH sent to this contract grants caller account a matching stake in contract. * Emits {Staked} event to reflect this. */ receive() external payable { stake(msg.value); } function stake(uint256 amount) public payable virtual override(IETHStakingRewards) updateReward(msg.sender) { require(amount > 0, "ETHPhase2Pool/ZeroStake"); require(amount == msg.value, "ETHPhase2Pool/IncorrectEth"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override(IETHStakingRewards) updateReward(msg.sender) { require(amount > 0, "ETHPhase2Pool/ZeroWithdraw"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); emit Withdrawn(msg.sender, amount); (bool success, ) = msg.sender.call{value: amount}(""); require(success, "ETHPhase2Pool/EthTransferFail"); } function exit() external override(IETHStakingRewards) { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public virtual override(IETHStakingRewards) updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- Reward Distributor ----- */ /** * @notice Should be called after the amount of reward tokens has been sent to the contract. Reward should be divisible by duration. * @param reward number of tokens to be distributed over the duration. */ function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } // Ensure provided reward amount is not more than the balance in the contract. // Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken // Reward + leftover < 1e18 uint256 balance = rewardToken.balanceOf(address(this)); require( rewardRate <= balance.div(DURATION), "ETHPhase2Pool/LowRewardBalance" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require( hasRole(RECOVER_ROLE, _msgSender()), "ETHPhase2Pool/HasRecoverRole" ); require(tokenAddress != address(rewardToken), "ETHPhase2Pool/NotReward"); IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IETHStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external payable; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "synthetix/contracts/interfaces/IStakingRewards.sol"; import "./RewardDistributionRecipient.sol"; /** * @title Base Reward Pool for Float Protocol * @notice This contract is used to reward `rewardToken` when `stakeToken` is staked. * @dev The Pools are based on the original Synthetix rewards contract (https://etherscan.io/address/0xDCB6A51eA3CA5d3Fd898Fd6564757c7aAeC3ca92#code) developed by @k06a which is battled tested and widely used. * Alterations: * - duration set on constructor (immutable) * - Internal properties rather than private * - Add virtual marker to functions * - Change stake / withdraw to external and provide internal equivalents * - Change require messages to match convention * - Add hooks for _beforeWithdraw and _beforeStake * - Emit events before external calls in line with best practices. */ abstract contract BasePool is IStakingRewards, AccessControl, RewardDistributionRecipient { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE"); uint256 public immutable duration; /* ========== STATE VARIABLES ========== */ IERC20 public rewardToken; IERC20 public stakeToken; uint256 public periodFinish; uint256 public rewardRate; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new BasePool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration ) RewardDistributionRecipient(_admin) { rewardDistribution = _rewardDistribution; rewardToken = IERC20(_rewardToken); stakeToken = IERC20(_stakingToken); duration = _duration; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(RECOVER_ROLE, _admin); } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Recovered(address token, uint256 amount); /* ========== MODIFIERS ========== */ modifier updateReward(address account) virtual { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== VIEWS ========== */ /** * @notice The total reward producing staked supply (total quantity to distribute) */ function totalSupply() public view virtual override(IStakingRewards) returns (uint256) { return _totalSupply; } /** * @notice The total reward producing balance of the account. */ function balanceOf(address account) public view virtual override(IStakingRewards) returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view virtual override(IStakingRewards) returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view virtual override(IStakingRewards) returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view virtual override(IStakingRewards) returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view override(IStakingRewards) returns (uint256) { return rewardRate.mul(duration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external virtual override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "BasePool/NonZeroStake"); _stake(msg.sender, msg.sender, amount); } function withdraw(uint256 amount) external virtual override(IStakingRewards) updateReward(msg.sender) { require(amount > 0, "BasePool/NonZeroWithdraw"); _withdraw(msg.sender, amount); } /** * @notice Exit the pool, taking any rewards due and staked */ function exit() external virtual override(IStakingRewards) updateReward(msg.sender) { _withdraw(msg.sender, _balances[msg.sender]); getReward(); } /** * @notice Retrieve any rewards due */ function getReward() public virtual override(IStakingRewards) updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; emit RewardPaid(msg.sender, reward); rewardToken.safeTransfer(msg.sender, reward); } } /** * @dev Stakes `amount` tokens from `staker` to `recipient`, increasing the total supply. * * Emits a {Staked} event. * * Requirements: * - `recipient` cannot be zero address. * - `staker` must have at least `amount` tokens * - `staker` must approve this contract for at least `amount` */ function _stake( address staker, address recipient, uint256 amount ) internal virtual { require(recipient != address(0), "BasePool/ZeroAddressS"); _beforeStake(staker, recipient, amount); _totalSupply = _totalSupply.add(amount); _balances[recipient] = _balances[recipient].add(amount); emit Staked(recipient, amount); stakeToken.safeTransferFrom(staker, address(this), amount); } /** * @dev Withdraws `amount` tokens from `account`, reducing the total supply. * * Emits a {Withdrawn} event. * * Requirements: * - `account` cannot be zero address. * - `account` must have at least `amount` staked. */ function _withdraw(address account, uint256 amount) internal virtual { require(account != address(0), "BasePool/ZeroAddressW"); _beforeWithdraw(account, amount); _balances[account] = _balances[account].sub( amount, "BasePool/WithdrawExceedsBalance" ); _totalSupply = _totalSupply.sub(amount); emit Withdrawn(account, amount); stakeToken.safeTransfer(account, amount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- Reward Distributor ----- */ /** * @notice Should be called after the amount of reward tokens has been sent to the contract. Reward should be divisible by duration. * @param reward number of tokens to be distributed over the duration. */ function notifyRewardAmount(uint256 reward) public virtual override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(duration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(duration); } // Ensure provided reward amount is not more than the balance in the contract. // Keeps reward rate within the right range to prevent overflows in earned or rewardsPerToken // Reward + leftover < 1e18 uint256 balance = rewardToken.balanceOf(address(this)); require(rewardRate <= balance.div(duration), "BasePool/InsufficentBalance"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(duration); emit RewardAdded(reward); } /* ----- RECOVER_ROLE ----- */ /** * @notice Provide accidental token retrieval. * @dev Sourced from synthetix/contracts/StakingRewards.sol */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external { require(hasRole(RECOVER_ROLE, _msgSender()), "BasePool/RecoverRole"); require(tokenAddress != address(stakeToken), "BasePool/NoRecoveryOfStake"); require( tokenAddress != address(rewardToken), "BasePool/NoRecoveryOfReward" ); emit Recovered(tokenAddress, tokenAmount); IERC20(tokenAddress).safeTransfer(_msgSender(), tokenAmount); } /* ========== HOOKS ========== */ /** * @dev Hook that is called before any staking of tokens. * * Calling conditions: * * - `amount` of ``staker``'s tokens will be staked into the pool * - `recipient` can withdraw. */ function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual {} /** * @dev Hook that is called before any staking of tokens. * * Calling conditions: * * - `amount` of ``from``'s tokens will be withdrawn into the pool */ function _beforeWithdraw(address from, uint256 amount) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "./BasePool.sol"; import "./extensions/DeadlinePool.sol"; import "./extensions/LockInPool.sol"; /** * Phase 4a Pool - is a special ceremony pool that can only be joined within the window period and has a Lock in period for the tokens */ contract Phase4aPool is DeadlinePool, LockInPool { /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new BasePool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _startWindow When ceremony starts * @param _endWindow When ceremony ends */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration, uint256 _startWindow, uint256 _endWindow ) DeadlinePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration, _startWindow, _endWindow ) {} // COMPILER HINTS for overrides function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual override(LockInPool, DeadlinePool) { super._beforeStake(staker, recipient, amount); } function _beforeWithdraw(address from, uint256 amount) internal virtual override(BasePool, LockInPool) { super._beforeWithdraw(from, amount); } function balanceOf(address account) public view virtual override(BasePool, LockInPool) returns (uint256) { return super.balanceOf(account); } function totalSupply() public view virtual override(BasePool, LockInPool) returns (uint256) { return super.totalSupply(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../BasePool.sol"; import "../../lib/Windowed.sol"; /** * @notice Only allow staking before the deadline. */ abstract contract DeadlinePool is BasePool, Windowed { constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration, uint256 _startWindow, uint256 _endWindow ) BasePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration ) Windowed(_startWindow, _endWindow) {} function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual override(BasePool) inWindow { super._beforeStake(staker, recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../BasePool.sol"; /** * Integrates a timelock of `LOCK_DURATION` on the Pool. * Can only withdraw from the pool if: * - not started * - or requested an unlock and waited the `LOCK_DURATION` * - or the rewards have finished for `REFILL_ALLOWANCE`. */ abstract contract LockInPool is BasePool { using SafeMath for uint256; uint256 private constant REFILL_ALLOWANCE = 2 hours; uint256 private constant LOCK_DURATION = 8 days; mapping(address => uint256) public unlocks; uint256 private _unlockingSupply; event Unlock(address indexed account); /* ========== VIEWS ========== */ /** * @notice The balance that is currently being unlocked * @param account The account we're interested in. */ function inLimbo(address account) public view returns (uint256) { if (unlocks[account] == 0) { return 0; } return super.balanceOf(account); } /// @inheritdoc BasePool function balanceOf(address account) public view virtual override(BasePool) returns (uint256) { if (unlocks[account] != 0) { return 0; } return super.balanceOf(account); } /// @inheritdoc BasePool function totalSupply() public view virtual override(BasePool) returns (uint256) { return super.totalSupply().sub(_unlockingSupply); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Request unlock of the token, removing this senders reward accural by: * - Setting balanceOf to return 0 (used for reward calculation) and adjusting total supply by amount unlocking. */ function unlock() external updateReward(msg.sender) { require(unlocks[msg.sender] == 0, "LockIn/UnlockOnce"); _unlockingSupply = _unlockingSupply.add(balanceOf(msg.sender)); unlocks[msg.sender] = block.timestamp; emit Unlock(msg.sender); } /* ========== HOOKS ========== */ /** * @notice Handle unlocks when staking, resets lock if was unlocking */ function _beforeStake( address staker, address recipient, uint256 amount ) internal virtual override(BasePool) { super._beforeStake(staker, recipient, amount); if (unlocks[recipient] != 0) { // If we are resetting an unlock, reset the unlockingSupply _unlockingSupply = _unlockingSupply.sub(inLimbo(recipient)); unlocks[recipient] = 0; } } /** * @dev Prevent withdrawal if: * - has started (i.e. rewards have entered the pool) * - before finished (+ allowance) * - not unlocked `LOCK_DURATION` ago * * - reset the unlock, so you can re-enter. */ function _beforeWithdraw(address recipient, uint256 amount) internal virtual override(BasePool) { super._beforeWithdraw(recipient, amount); // Before rewards have been added / after + `REFILL` bool releaseWithoutLock = block.timestamp >= periodFinish.add(REFILL_ALLOWANCE); // A lock has been requested and the `LOCK_DURATION` has passed. bool releaseWithLock = (unlocks[recipient] != 0) && (unlocks[recipient] <= block.timestamp.sub(LOCK_DURATION)); require(releaseWithoutLock || releaseWithLock, "LockIn/NotReleased"); if (unlocks[recipient] != 0) { // Reduce unlocking supply (so we don't keep discounting total supply when // it is reduced). Amount will be validated in withdraw proper. _unlockingSupply = _unlockingSupply.sub(amount); } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "./extensions/LockInPool.sol"; /** * Phase4Pool that acts as a SNX Reward Contract, with an 8 day token lock. */ contract Phase4Pool is LockInPool { /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Phase4Pool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _duration Duration for token */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration ) BasePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration ) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IMasterChefRewarder.sol"; import "../BasePool.sol"; // !!!! WIP !!!!! // This code doesn't work. You can deposit via sushi, withdraw through normal functions. // Must separate the balances and only keep them the same for the rewards. /** * Provides adapters to allow this reward contract to be used as a MASTERCHEF V2 Rewards contract */ abstract contract MasterChefV2Pool is BasePool, IMasterChefRewarder { using SafeMath for uint256; address private immutable masterchefV2; /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new MasterChefV2Pool * @param _admin The default role controller * @param _rewardDistribution The reward distributor (can change reward rate) * @param _rewardToken The reward token to distribute * @param _stakingToken The staking token used to qualify for rewards * @param _duration The duration for each reward distribution * @param _masterchefv2 The trusted masterchef contract */ constructor( address _admin, address _rewardDistribution, address _rewardToken, address _stakingToken, uint256 _duration, address _masterchefv2 ) BasePool( _admin, _rewardDistribution, _rewardToken, _stakingToken, _duration ) { masterchefV2 = _masterchefv2; } /* ========== MODIFIERS ========== */ modifier onlyMCV2 { require(msg.sender == masterchefV2, "MasterChefV2Pool/OnlyMCV2"); _; } /* ========== VIEWS ========== */ function pendingTokens( uint256, address user, uint256 ) external view override(IMasterChefRewarder) returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts) { IERC20[] memory _rewardTokens = new IERC20[](1); _rewardTokens[0] = (rewardToken); uint256[] memory _rewardAmounts = new uint256[](1); _rewardAmounts[0] = earned(user); return (_rewardTokens, _rewardAmounts); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * Adds to the internal balance record, */ function onSushiReward( uint256, address _user, address, uint256, uint256 newLpAmount ) external override(IMasterChefRewarder) onlyMCV2 updateReward(_user) { uint256 internalBalance = _balances[_user]; if (internalBalance > newLpAmount) { // _withdrawWithoutPush(_user, internalBalance.sub(newLpAmount)); } else if (internalBalance < newLpAmount) { // _stakeWithoutPull(_user, _user, newLpAmount.sub(internalBalance)); } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IMasterChefRewarder { function onSushiReward( uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount ) external; function pendingTokens( uint256 pid, address user, uint256 sushiAmount ) external view returns (IERC20[] memory, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../interfaces/ISupplyControlledERC20.sol"; import "hardhat/console.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * This has an open mint functionality */ // ISupplyControlledERC20, contract SupplyControlledTokenMock is AccessControl, ERC20Burnable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor( address _admin, string memory _name, string memory _symbol, uint8 _decimals ) ERC20(_name, _symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(MINTER_ROLE, _admin); _setupDecimals(_decimals); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * */ function mint(address to, uint256 amount) external { require(hasRole(MINTER_ROLE, _msgSender()), "SCTokenMock/MinterRole"); _mint(to, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { // console.log(symbol(), from, "->", to); // console.log(symbol(), ">", amount); super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: BSD-3-Clause // Copyright 2020 Compound Labs, Inc. pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "hardhat/console.sol"; contract TimeLock { using SafeMath for uint256; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant MINIMUM_DELAY = 2 days; uint256 public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint256 public delay; mapping(bytes32 => bool) public queuedTransactions; constructor(address admin_, uint256 delay_) public { require( delay_ >= MINIMUM_DELAY, "TimeLock::constructor: Delay must exceed minimum delay." ); require( delay_ <= MAXIMUM_DELAY, "TimeLock::constructor: Delay must not exceed maximum delay." ); admin = admin_; delay = delay_; } fallback() external {} function setDelay(uint256 delay_) public { require( msg.sender == address(this), "TimeLock::setDelay: Call must come from TimeLock." ); require( delay_ >= MINIMUM_DELAY, "TimeLock::setDelay: Delay must exceed minimum delay." ); require( delay_ <= MAXIMUM_DELAY, "TimeLock::setDelay: Delay must not exceed maximum delay." ); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require( msg.sender == pendingAdmin, "TimeLock::acceptAdmin: Call must come from pendingAdmin." ); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { require( msg.sender == address(this), "TimeLock::setPendingAdmin: Call must come from TimeLock." ); pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public returns (bytes32) { require( msg.sender == admin, "TimeLock::queueTransaction: Call must come from admin." ); require( eta >= getBlockTimestamp().add(delay), "TimeLock::queueTransaction: Estimated execution block must satisfy delay." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public { require( msg.sender == admin, "TimeLock::cancelTransaction: Call must come from admin." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public payable returns (bytes memory) { require( msg.sender == admin, "TimeLock::executeTransaction: Call must come from admin." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require( queuedTransactions[txHash], "TimeLock::executeTransaction: Transaction hasn't been queued." ); require( getBlockTimestamp() >= eta, "TimeLock::executeTransaction: Transaction hasn't surpassed time lock." ); require( getBlockTimestamp() <= eta.add(GRACE_PERIOD), "TimeLock::executeTransaction: Transaction is stale." ); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(callData); require( success, "TimeLock::executeTransaction: Transaction execution reverted." ); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } } // SPDX-License-Identifier: BSD-3-Clause // Copyright 2020 Compound Labs, Inc. pragma solidity ^0.7.6; import "../TimeLock.sol"; contract TimeLockMock is TimeLock { constructor(address admin_, uint256 delay_) TimeLock(admin_, TimeLock.MINIMUM_DELAY) { admin = admin_; delay = delay_; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "synthetix/contracts/interfaces/IStakingRewards.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract EarnedAggregator { /// @notice The address of the Float Protocol Timelock address public timelock; /// @notice addresses of pools (Staking Rewards Contracts) address[] public pools; constructor(address timelock_, address[] memory pools_) { timelock = timelock_; pools = pools_; } function getPools() public view returns (address[] memory) { address[] memory pls = pools; return pls; } function addPool(address pool) public { // Sanity check for function and no error IStakingRewards(pool).earned(timelock); for (uint256 i = 0; i < pools.length; i++) { require(pools[i] != pool, "already added"); } require(msg.sender == address(timelock), "EarnedAggregator: !timelock"); pools.push(pool); } function removePool(uint256 index) public { require(msg.sender == address(timelock), "EarnedAggregator: !timelock"); if (index >= pools.length) return; if (index != pools.length - 1) { pools[index] = pools[pools.length - 1]; } pools.pop(); } function getCurrentEarned(address account) public view returns (uint256) { uint256 votes = 0; for (uint256 i = 0; i < pools.length; i++) { // get tokens earned for staking votes = SafeMath.add(votes, IStakingRewards(pools[i]).earned(account)); } return votes; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../AuctionHouseMath.sol"; contract AuctionHouseMathTest is AuctionHouseMath { function _lerp( uint256 start, uint256 end, uint16 step, uint16 maxStep ) public pure returns (uint256 result) { return lerp(start, end, step, maxStep); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../external-lib/SafeDecimalMath.sol"; import "./interfaces/IBasket.sol"; import "./BasketMath.sol"; /** * @title Float Protocol Basket * @notice The logic contract for storing underlying ETH (as wETH) */ contract BasketV1 is IBasket, Initializable, AccessControlUpgradeable { using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant AUCTION_HOUSE_ROLE = keccak256("AUCTION_HOUSE_ROLE"); /* ========== STATE VARIABLES ========== */ IERC20 public float; IERC20 private weth; /** * @notice The target ratio for "collateralisation" * @dev [e27] Start at 100% */ uint256 public targetRatio; function initialize( address _admin, address _weth, address _float ) external initializer { weth = IERC20(_weth); float = IERC20(_float); targetRatio = SafeDecimalMath.PRECISE_UNIT; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(GOVERNANCE_ROLE, _admin); } /* ========== MODIFIERS ========== */ modifier onlyGovernance { require( hasRole(GOVERNANCE_ROLE, _msgSender()), "AuctionHouse/GovernanceRole" ); _; } /* ========== VIEWS ========== */ /// @inheritdoc IBasketReader function underlying() public view override(IBasketReader) returns (address) { return address(weth); } /// @inheritdoc IBasketReader function getBasketFactor(uint256 targetPriceInEth) external view override(IBasketReader) returns (uint256 basketFactor) { uint256 wethInBasket = weth.balanceOf(address(this)); uint256 floatTotalSupply = float.totalSupply(); return basketFactor = BasketMath.calcBasketFactor( targetPriceInEth, wethInBasket, floatTotalSupply, targetRatio ); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ----- onlyGovernance ----- */ /// @inheritdoc IBasketGovernedActions function buildAuctionHouse(address _auctionHouse, uint256 _allowance) external override(IBasketGovernedActions) onlyGovernance { grantRole(AUCTION_HOUSE_ROLE, _auctionHouse); weth.safeApprove(_auctionHouse, 0); weth.safeApprove(_auctionHouse, _allowance); } /// @inheritdoc IBasketGovernedActions function burnAuctionHouse(address _auctionHouse) external override(IBasketGovernedActions) onlyGovernance { revokeRole(AUCTION_HOUSE_ROLE, _auctionHouse); weth.safeApprove(_auctionHouse, 0); } /// @inheritdoc IBasketGovernedActions function setTargetRatio(uint256 _targetRatio) external override(IBasketGovernedActions) onlyGovernance { require( _targetRatio <= BasketMath.MAX_TARGET_RATIO, "BasketV1/RatioTooHigh" ); require( _targetRatio >= BasketMath.MIN_TARGET_RATIO, "BasketV1/RatioTooLow" ); targetRatio = _targetRatio; emit NewTargetRatio(_targetRatio); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; import "./basket/IBasketReader.sol"; import "./basket/IBasketGovernedActions.sol"; /** * @title The interface for a Float Protocol Asset Basket * @notice A Basket stores value used to stabilise price and assess the * the movement of the underlying assets we're trying to track. * @dev The Basket interface is broken up into many smaller pieces to allow only * relevant parts to be imported */ interface IBasket is IBasketReader, IBasketGovernedActions { } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../external-lib/SafeDecimalMath.sol"; library BasketMath { using SafeMath for uint256; using SafeDecimalMath for uint256; // SafeDecimalMath.PRECISE_UNIT = 1e27 uint256 internal constant MIN_TARGET_RATIO = 0.1e27; uint256 internal constant MAX_TARGET_RATIO = 2e27; /** * @dev bF = ( eS / (fS * tP) ) / Q * @param targetPriceInEth [e27] target price (tP). * @param ethStored [e18] denoting total eth stored in basket (eS). * @param floatSupply [e18] denoting total floatSupply (fS). * @param targetRatio [e27] target ratio (Q) * @return basketFactor an [e27] decimal (bF) */ function calcBasketFactor( uint256 targetPriceInEth, uint256 ethStored, uint256 floatSupply, uint256 targetRatio ) internal pure returns (uint256 basketFactor) { // Note that targetRatio should already be checked on set assert(targetRatio >= MIN_TARGET_RATIO); assert(targetRatio <= MAX_TARGET_RATIO); uint256 floatValue = floatSupply.multiplyDecimalRoundPrecise(targetPriceInEth); uint256 basketRatio = ethStored.divideDecimalRoundPrecise(floatValue); return basketFactor = basketRatio.divideDecimalRoundPrecise(targetRatio); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; /** * @title Basket Actions with suitable access control * @notice Contains actions which can only be called by governance. */ interface IBasketGovernedActions { event NewTargetRatio(uint256 targetRatio); /** * @notice Sets the basket target factor, initially "1" * @dev Expects an [e27] fixed point decimal value. * Target Ratio is what the basket factor is "aiming for", * i.e. target ratio = 0.8 then an 80% support from the basket * results in a 100% Basket Factor. * @param _targetRatio [e27] The new Target ratio */ function setTargetRatio(uint256 _targetRatio) external; /** * @notice Connect and approve a new auction house to spend from the basket. * @dev Note that any allowance can be set, and even type(uint256).max will * slowly be eroded. * @param _auctionHouse The Auction House address to approve * @param _allowance The amount of the underlying token it can spend */ function buildAuctionHouse(address _auctionHouse, uint256 _allowance) external; /** * @notice Remove an auction house, allows easy upgrades. * @param _auctionHouse The Auction House address to revoke. */ function burnAuctionHouse(address _auctionHouse) external; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../BasketMath.sol"; contract BasketMathHarness { function _calcBasketFactor( uint256 targetPriceInEth, uint256 ethStored, uint256 floatSupply, uint256 targetRatio ) external pure returns (uint256 basketFactor) { return BasketMath.calcBasketFactor( targetPriceInEth, ethStored, floatSupply, targetRatio ); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title {ERC20} Pausable token through the PAUSER_ROLE * * @dev This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions using the different roles. */ abstract contract ERC20PausableUpgradeable is Initializable, PausableUpgradeable, AccessControlUpgradeable, ERC20Upgradeable { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __ERC20Pausable_init_unchained(address pauser) internal initializer { _setupRole(PAUSER_ROLE, pauser); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() external { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20Pausable/PauserRoleRequired" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() external { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20Pausable/PauserRoleRequired" ); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable/Paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "./ERC20PermitUpgradeable.sol"; import "./ERC20PausableUpgradeable.sol"; import "./ERC20SupplyControlledUpgradeable.sol"; /** * @dev {ERC20} FLOAT token, including: * * - a minter role that allows for token minting (necessary for stabilisation) * - the ability to burn tokens (necessary for stabilisation) * - the use of permits to reduce gas costs * - a pauser role that allows to stop all token transfers * * This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions * using the different roles. * This contract is upgradable. */ contract FloatTokenV1 is ERC20PausableUpgradeable, ERC20PermitUpgradeable, ERC20SupplyControlledUpgradeable { /** * @notice Construct a FloatTokenV1 instance * @param governance The default role controller, minter and pauser for the contract. * @param minter An additional minter (useful for quick launches, check this is revoked) * @dev We expect minters to be defined on deploy, e.g. AuctionHouse should get minter role */ function initialize(address governance, address minter) external initializer { __Context_init_unchained(); __ERC20_init_unchained("Float Protocol: FLOAT", "FLOAT"); __ERC20Permit_init_unchained("Float Protocol: FLOAT", "1"); __ERC20Pausable_init_unchained(governance); __ERC20SupplyControlled_init_unchained(governance); _setupRole(DEFAULT_ADMIN_ROLE, governance); // Quick launches _setupRole(MINTER_ROLE, minter); } /// @dev Hint to compiler, that this override has already occured. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../external-lib/Counters.sol"; import "../external-lib/EIP712.sol"; import "./interfaces/IERC20Permit.sol"; /** * @dev Wrapper implementation for ERC20 Permit extension allowing approvals * via signatures, as defined in https://eips.ethereum.org/EIPS/eip-2612. */ contract ERC20PermitUpgradeable is IERC20Permit, Initializable, ERC20Upgradeable { using Counters for Counters.Counter; bytes32 private constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 internal _domainSeparator; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line func-name-mixedcase function __ERC20Permit_init_unchained( string memory domainName, string memory version ) internal initializer { _domainSeparator = EIP712.domainSeparatorV4(domainName, version); } /// @inheritdoc IERC20Permit // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override(IERC20Permit) returns (bytes32) { return _domainSeparator; } /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override(IERC20Permit) { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit/ExpiredDeadline"); bytes32 structHash = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = EIP712.hashTypedDataV4(_domainSeparator, structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit/InvalidSignature"); _approve(owner, spender, value); } /// @inheritdoc IERC20Permit function nonces(address owner) external view virtual override(IERC20Permit) returns (uint256) { return _nonces[owner].current(); } /** * @dev "Consume a nonce": return the current value and increment. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title {ERC20} Supply Controlled token that allows burning (by all), and minting * by MINTER_ROLE * * @dev This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions using the different roles. */ abstract contract ERC20SupplyControlledUpgradeable is Initializable, AccessControlUpgradeable, ERC20Upgradeable { using SafeMath for uint256; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __ERC20SupplyControlled_init_unchained(address minter) internal initializer { _setupRole(MINTER_ROLE, minter); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) external virtual { require( hasRole(MINTER_ROLE, _msgSender()), "ERC20SupplyControlled/MinterRole" ); _mint(to, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external 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) external virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20SupplyControlled/Overburn" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /** * @title Counters * @author Matt Condon (@shrugs) https://github.com/OpenZeppelin/openzeppelin-contracts * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); counter._value = value - 1; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "./ECDSA.sol"; // Based on OpenZeppelin's draft EIP712, with updates to remove storage variables. /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * */ library EIP712 { bytes32 private constant _TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /** * @dev Returns the domain separator for the current chain. */ function domainSeparatorV4(string memory name, string memory version) internal view returns (bytes32) { return _buildDomainSeparator( _TYPE_HASH, keccak256(bytes(name)), keccak256(bytes(version)) ); } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return keccak256(abi.encode(typeHash, name, version, chainId, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for the given domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = EIP712.hashTypedDataV4( * EIP712.domainSeparatorV4("DApp Name", "1"), * keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function hashTypedDataV4(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return ECDSA.toTypedDataHash(domainSeparator, structHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /** * @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. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // 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) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } 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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @dev {ERC20} BANK token, including: * * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions * using the different roles. * This contract is upgradable. */ contract BankToken is Initializable, PausableUpgradeable, AccessControlUpgradeable, ERC20Upgradeable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** @notice Construct a BankToken instance @param admin The default role controller, minter and pauser for the contract. @param minter An additional minter (for quick launch of epoch 1). */ function initialize(address admin, address minter) public initializer { __ERC20_init("Float Bank", "BANK"); _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(MINTER_ROLE, admin); _setupRole(MINTER_ROLE, minter); _setupRole(PAUSER_ROLE, admin); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "Bank::mint: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "Bank::pause: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "Bank::unpause: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../lib/Upgradeable.sol"; import "./ERC20PermitUpgradeable.sol"; import "./ERC20PausableUpgradeable.sol"; import "./ERC20SupplyControlledUpgradeable.sol"; /** * @dev {ERC20} BANK token, including: * * - a minter role that allows for token minting (necessary for stabilisation) * - the ability to burn tokens (necessary for stabilisation) * - the use of permits to reduce gas costs * - a pauser role that allows to stop all token transfers * * This contract uses OpenZeppelin {AccessControlUpgradeable} to lock permissioned functions * using the different roles. * This contract is upgradable. */ contract BankTokenV2 is ERC20PausableUpgradeable, ERC20PermitUpgradeable, ERC20SupplyControlledUpgradeable, Upgradeable { /** * @notice Construct a brand new BankTokenV2 instance * @param governance The default role controller, minter and pauser for the contract. * @dev We expect minters to be defined after deploy, e.g. AuctionHouse should get minter role */ function initialize(address governance) external initializer { _version = 2; __Context_init_unchained(); __ERC20_init_unchained("Float Bank", "BANK"); __ERC20Permit_init_unchained("Float Protocol: BANK", "2"); __ERC20Pausable_init_unchained(governance); __ERC20SupplyControlled_init_unchained(governance); _setupRole(DEFAULT_ADMIN_ROLE, governance); } /** * @notice Upgrade from V1, and initialise the relevant "new" state * @dev Uses upgradeAndCall in the ProxyAdmin, to call upgradeToAndCall, which will delegatecall this function. * _version keeps this single use * onlyProxyAdmin ensures this only occurs on upgrade */ function upgrade() external onlyProxyAdmin { require(_version < 2, "BankTokenV2/AlreadyUpgraded"); _version = 2; _domainSeparator = EIP712.domainSeparatorV4("Float Protocol: BANK", "2"); } /// @dev Hint to compiler that this override has already occured. function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; /** * @title Upgradeable * @dev This contract provides special helper functions when using the upgradeability proxy. */ abstract contract Upgradeable { uint256 internal _version; /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; modifier onlyProxyAdmin() { address proxyAdmin; bytes32 slot = ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { proxyAdmin := sload(slot) } require(msg.sender == proxyAdmin, "Upgradeable/MustBeProxyAdmin"); _; } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "../BasisMath.sol"; contract BasisMathMock { using BasisMath for uint256; function _splitBy(uint256 value, uint256 percentage) public pure returns (uint256, uint256) { return value.splitBy(percentage); } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper // SPDX-License-Identifier: GPLv2 // Changes: // - Conversion to 0.7.6 // - library imports throughout // - remove revert fallback as now default import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; pragma solidity ^0.7.6; contract ZapBaseV1 is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; bool public stopped = false; // if true, goodwill is not deducted mapping(address => bool) public feeWhitelist; uint256 public goodwill; // % share of goodwill (0-100 %) uint256 affiliateSplit; // restrict affiliates mapping(address => bool) public affiliates; // affiliate => token => amount mapping(address => mapping(address => uint256)) public affiliateBalance; // token => amount mapping(address => uint256) public totalAffiliateBalance; address internal constant ETHAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; constructor(uint256 _goodwill, uint256 _affiliateSplit) { goodwill = _goodwill; affiliateSplit = _affiliateSplit; } // circuit breaker modifiers modifier stopInEmergency { if (stopped) { revert("Temporarily Paused"); } else { _; } } function _getBalance(address token) internal view returns (uint256 balance) { if (token == address(0)) { balance = address(this).balance; } else { balance = IERC20(token).balanceOf(address(this)); } } function _approveToken(address token, address spender) internal { IERC20 _token = IERC20(token); if (_token.allowance(address(this), spender) > 0) return; else { _token.safeApprove(spender, uint256(-1)); } } function _approveToken( address token, address spender, uint256 amount ) internal { IERC20 _token = IERC20(token); _token.safeApprove(spender, 0); _token.safeApprove(spender, amount); } // - to Pause the contract function toggleContractActive() public onlyOwner { stopped = !stopped; } function set_feeWhitelist(address zapAddress, bool status) external onlyOwner { feeWhitelist[zapAddress] = status; } function set_new_goodwill(uint256 _new_goodwill) public onlyOwner { require( _new_goodwill >= 0 && _new_goodwill <= 100, "GoodWill Value not allowed" ); goodwill = _new_goodwill; } function set_new_affiliateSplit(uint256 _new_affiliateSplit) external onlyOwner { require(_new_affiliateSplit <= 100, "Affiliate Split Value not allowed"); affiliateSplit = _new_affiliateSplit; } function set_affiliate(address _affiliate, bool _status) external onlyOwner { affiliates[_affiliate] = _status; } ///@notice Withdraw goodwill share, retaining affilliate share function withdrawTokens(address[] calldata tokens) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 qty; if (tokens[i] == ETHAddress) { qty = address(this).balance.sub(totalAffiliateBalance[tokens[i]]); Address.sendValue(payable(owner()), qty); } else { qty = IERC20(tokens[i]).balanceOf(address(this)).sub( totalAffiliateBalance[tokens[i]] ); IERC20(tokens[i]).safeTransfer(owner(), qty); } } } ///@notice Withdraw affilliate share, retaining goodwill share function affilliateWithdraw(address[] calldata tokens) external { uint256 tokenBal; for (uint256 i = 0; i < tokens.length; i++) { tokenBal = affiliateBalance[msg.sender][tokens[i]]; affiliateBalance[msg.sender][tokens[i]] = 0; totalAffiliateBalance[tokens[i]] = totalAffiliateBalance[tokens[i]].sub( tokenBal ); if (tokens[i] == ETHAddress) { Address.sendValue(msg.sender, tokenBal); } else { IERC20(tokens[i]).safeTransfer(msg.sender, tokenBal); } } } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper // SPDX-License-Identifier: GPLv2 // Changes: // - Conversion to 0.7.6 // - abstract type // - library imports throughout pragma solidity ^0.7.6; import "./ZapBaseV1.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; abstract contract ZapInBaseV2 is ZapBaseV1 { using SafeMath for uint256; using SafeERC20 for IERC20; function _pullTokens( address token, uint256 amount, address affiliate, bool enableGoodwill, bool shouldSellEntireBalance ) internal returns (uint256 value) { uint256 totalGoodwillPortion; if (token == address(0)) { require(msg.value > 0, "No eth sent"); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( ETHAddress, msg.value, affiliate, enableGoodwill ); return msg.value.sub(totalGoodwillPortion); } require(amount > 0, "Invalid token amount"); require(msg.value == 0, "Eth sent with token"); //transfer token if (shouldSellEntireBalance) { require( Address.isContract(msg.sender), "ERR: shouldSellEntireBalance is true for EOA" ); amount = IERC20(token).allowance(msg.sender, address(this)); } IERC20(token).safeTransferFrom(msg.sender, address(this), amount); // subtract goodwill totalGoodwillPortion = _subtractGoodwill( token, amount, affiliate, enableGoodwill ); return amount.sub(totalGoodwillPortion); } function _subtractGoodwill( address token, uint256 amount, address affiliate, bool enableGoodwill ) internal returns (uint256 totalGoodwillPortion) { bool whitelisted = feeWhitelist[msg.sender]; if (enableGoodwill && !whitelisted && goodwill > 0) { totalGoodwillPortion = SafeMath.div( SafeMath.mul(amount, goodwill), 10000 ); if (affiliates[affiliate]) { if (token == address(0)) { token = ETHAddress; } uint256 affiliatePortion = totalGoodwillPortion.mul(affiliateSplit).div(100); affiliateBalance[affiliate][token] = affiliateBalance[affiliate][token] .add(affiliatePortion); totalAffiliateBalance[token] = totalAffiliateBalance[token].add( affiliatePortion ); } } } } // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2021 zapper // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper // SPDX-License-Identifier: GPLv2 // Changes: // - Uses msg.sender / removes the transfer from the zap contract. // - Uses IMintingCeremony over IVault pragma solidity =0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../funds/interfaces/IMintingCeremony.sol"; import "../external-lib/zapper/ZapInBaseV2.sol"; contract FloatMintingCeremonyZapInV1 is ZapInBaseV2 { using SafeMath for uint256; // calldata only accepted for approved zap contracts mapping(address => bool) public approvedTargets; event zapIn(address sender, address pool, uint256 tokensRec); constructor(uint256 _goodwill, uint256 _affiliateSplit) ZapBaseV1(_goodwill, _affiliateSplit) {} /** @notice This function commits to the Float Minting Ceremony with ETH or ERC20 tokens @param fromToken The token used for entry (address(0) if ether) @param amountIn The amount of fromToken to invest @param ceremony Float Protocol: Minting Ceremony address @param minFloatTokens The minimum acceptable quantity Float tokens to receive. Reverts otherwise @param intermediateToken Token to swap fromToken to before entering ceremony @param swapTarget Excecution target for the swap or zap @param swapData DEX or Zap data @param affiliate Affiliate address @return tokensReceived - Quantity of FLOAT that will be received */ function ZapIn( address fromToken, uint256 amountIn, address ceremony, uint256 minFloatTokens, address intermediateToken, address swapTarget, bytes calldata swapData, address affiliate, bool shouldSellEntireBalance ) external payable stopInEmergency returns (uint256 tokensReceived) { require( approvedTargets[swapTarget] || swapTarget == address(0), "Target not Authorized" ); // get incoming tokens uint256 toInvest = _pullTokens( fromToken, amountIn, affiliate, true, shouldSellEntireBalance ); // get intermediate token uint256 intermediateAmt = _fillQuote(fromToken, intermediateToken, toInvest, swapTarget, swapData); // Deposit to Minting Ceremony tokensReceived = _ceremonyCommit(intermediateAmt, ceremony, minFloatTokens); } function _ceremonyCommit( uint256 amount, address toCeremony, uint256 minTokensRec ) internal returns (uint256 tokensReceived) { address underlyingVaultToken = IMintingCeremony(toCeremony).underlying(); _approveToken(underlyingVaultToken, toCeremony); uint256 initialBal = IERC20(toCeremony).balanceOf(msg.sender); IMintingCeremony(toCeremony).commit(msg.sender, amount, minTokensRec); tokensReceived = IERC20(toCeremony).balanceOf(msg.sender).sub(initialBal); require(tokensReceived >= minTokensRec, "Err: High Slippage"); // Note that tokens are gifted directly, so we don't transfer from vault. // IERC20(toCeremony).safeTransfer(msg.sender, tokensReceived); emit zapIn(msg.sender, toCeremony, tokensReceived); } function _fillQuote( address _fromTokenAddress, address toToken, uint256 _amount, address _swapTarget, bytes memory swapCallData ) internal returns (uint256 amtBought) { uint256 valueToSend; if (_fromTokenAddress == toToken) { return _amount; } if (_fromTokenAddress == address(0)) { valueToSend = _amount; } else { _approveToken(_fromTokenAddress, _swapTarget); } uint256 iniBal = _getBalance(toToken); (bool success, ) = _swapTarget.call{value: valueToSend}(swapCallData); require(success, "Error Swapping Tokens 1"); uint256 finalBal = _getBalance(toToken); amtBought = finalBal.sub(iniBal); } function setApprovedTargets( address[] calldata targets, bool[] calldata isApproved ) external onlyOwner { require(targets.length == isApproved.length, "Invalid Input length"); for (uint256 i = 0; i < targets.length; i++) { approvedTargets[targets[i]] = isApproved[i]; } } } // SPDX-License-Identifier: MIT pragma solidity =0.7.6; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/FixedPoint.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../external-lib/UniswapV2Library.sol"; import "../external-lib/UniswapV2OracleLibrary.sol"; import "../lib/SushiswapLibrary.sol"; import "./interfaces/ITwap.sol"; // As these are "Time"-Weighted Average Price contracts, they necessarily rely on time. // solhint-disable not-rely-on-time /** * @title A sliding window for AMMs (specifically Sushiswap) * @notice Uses observations collected over a window to provide moving price averages in the past * @dev This is a singleton TWAP that only needs to be deployed once per desired parameters. `windowSize` has a precision of `windowSize / granularity` * Errors: * MissingPastObsr - We do not have suffient past observations. * UnexpectedElapsed - We have an unexpected time elapsed. * EarlyUpdate - Tried to update the TWAP before the period has elapsed. * InvalidToken - Cannot consult an invalid token pair. */ contract Twap is ITwap { using FixedPoint for *; using SafeMath for uint256; struct Observation { uint256 timestamp; uint256 price0Cumulative; uint256 price1Cumulative; } /* ========== IMMUTABLE VARIABLES ========== */ /// @notice the Uniswap Factory contract for tracking exchanges address public immutable factory; /// @notice The desired amount of time over which the moving average should be computed, e.g. 24 hours uint256 public immutable windowSize; /// @notice The number of observations stored for each pair, i.e. how many price observations are stored for the window /// @dev As granularity increases from, more frequent updates are needed; but precision increases [`windowSize - (windowSize / granularity) * 2`, `windowSize`] uint8 public immutable granularity; /// @dev Redundant with `granularity` and `windowSize`, but has gas savings & easy read uint256 public immutable periodSize; /* ========== STATE VARIABLES ========== */ /// @notice Mapping from pair address to a list of price observations of that pair mapping(address => Observation[]) public pairObservations; /* ========== EVENTS ========== */ event NewObservation( uint256 timestamp, uint256 price0Cumulative, uint256 price1Cumulative ); /* ========== CONSTRUCTOR ========== */ /** * @notice Construct a new Sliding Window TWAP * @param factory_ The AMM factory * @param windowSize_ The window size for this TWAP * @param granularity_ The granularity required for the TWAP */ constructor( address factory_, uint256 windowSize_, uint8 granularity_ ) { require(factory_ != address(0), "Twap/InvalidFactory"); require(granularity_ > 1, "Twap/Granularity"); require( (periodSize = windowSize_ / granularity_) * granularity_ == windowSize_, "Twap/WindowSize" ); factory = factory_; windowSize = windowSize_; granularity = granularity_; } /* ========== PURE ========== */ /** * @notice Given the cumulative prices of the start and end of a period, and the length of the period, compute the average price in terms of the amount in * @param priceCumulativeStart the cumulative price for the start of the period * @param priceCumulativeEnd the cumulative price for the end of the period * @param timeElapsed the time from now to the first observation * @param amountIn the amount of tokens in * @return amountOut amount out received for the amount in */ function _computeAmountOut( uint256 priceCumulativeStart, uint256 priceCumulativeEnd, uint256 timeElapsed, uint256 amountIn ) private pure returns (uint256 amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } /* ========== VIEWS ========== */ /** * @notice Calculates the index of the observation for the given `timestamp` * @param timestamp the observation for the timestamp * @return index The index of the observation */ function observationIndexOf(uint256 timestamp) public view returns (uint8 index) { uint256 epochPeriod = timestamp / periodSize; return uint8(epochPeriod % granularity); } /// @inheritdoc ITwap function updateable(address tokenA, address tokenB) external view override(ITwap) returns (bool) { address pair = SushiswapLibrary.pairFor(factory, tokenA, tokenB); uint8 observationIndex = observationIndexOf(block.timestamp); Observation storage observation = pairObservations[pair][observationIndex]; // We only want to commit updates once per period (i.e. windowSize / granularity). uint256 timeElapsed = block.timestamp - observation.timestamp; return timeElapsed > periodSize; } /// @inheritdoc ITwap function consult( address tokenIn, uint256 amountIn, address tokenOut ) external view override(ITwap) returns (uint256 amountOut) { address pair = SushiswapLibrary.pairFor(factory, tokenIn, tokenOut); Observation storage firstObservation = _getFirstObservationInWindow(pair); uint256 timeElapsed = block.timestamp - firstObservation.timestamp; require(timeElapsed <= windowSize, "Twap/MissingPastObsr"); require( timeElapsed >= windowSize - periodSize * 2, "Twap/UnexpectedElapsed" ); (uint256 price0Cumulative, uint256 price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair); (address token0, address token1) = UniswapV2Library.sortTokens(tokenIn, tokenOut); if (token0 == tokenIn) { return _computeAmountOut( firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn ); } require(token1 == tokenIn, "Twap/InvalidToken"); return _computeAmountOut( firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn ); } /** * @notice Observation from the oldest epoch (at the beginning of the window) relative to the current time * @param pair the Uniswap pair address * @return firstObservation The observation from the oldest epoch relative to current time. */ function _getFirstObservationInWindow(address pair) private view returns (Observation storage firstObservation) { uint8 observationIndex = observationIndexOf(block.timestamp); // No overflow issues; if observationIndex + 1 overflows, result is still zero. uint8 firstObservationIndex = (observationIndex + 1) % granularity; firstObservation = pairObservations[pair][firstObservationIndex]; } /* ========== MUTATIVE FUNCTIONS ========== */ /// @inheritdoc ITwap function update(address tokenA, address tokenB) external override(ITwap) returns (bool) { address pair = SushiswapLibrary.pairFor(factory, tokenA, tokenB); // Populate the array with empty observations for the first call. for (uint256 i = pairObservations[pair].length; i < granularity; i++) { pairObservations[pair].push(); } // Get the observation for the current period. uint8 observationIndex = observationIndexOf(block.timestamp); Observation storage observation = pairObservations[pair][observationIndex]; // We only want to commit updates once per period (i.e. windowSize / granularity). uint256 timeElapsed = block.timestamp - observation.timestamp; if (timeElapsed <= periodSize) { // Skip update as we're in the same observation slot. return false; } (uint256 price0Cumulative, uint256 price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observation.timestamp = block.timestamp; observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; emit NewObservation( observation.timestamp, observation.price0Cumulative, observation.price1Cumulative ); return true; } } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.4.0; // 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; // 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); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint256; // 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"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 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( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 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( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 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( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 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, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/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 ( uint256 price0Cumulative, uint256 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 += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../external-lib/UniswapV2Library.sol"; library SushiswapLibrary { // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ); } } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.7.6; pragma abicoder v2; import "../MonetaryPolicyV1.sol"; contract MonetaryPolicyV1Harness is MonetaryPolicyV1 { uint256 public blockNumber; constructor(address _governance, address _ethUsdOracle) MonetaryPolicyV1(_governance, _ethUsdOracle) {} function _blockNumber() internal view override returns (uint256) { return blockNumber; } function __setBlock(uint256 _number) external { blockNumber = _number; } }
* @notice Constructs a new Minting Ceremony/
) Windowed(ceremonyStart, ceremonyStart + CEREMONY_DURATION) { require(governance_ != address(0), "MC/ZeroAddress"); require(monetaryPolicy_ != address(0), "MC/ZeroAddress"); require(basket_ != address(0), "MC/ZeroAddress"); require(float_ != address(0), "MC/ZeroAddress"); monetaryPolicy = IMonetaryPolicy(monetaryPolicy_); basket = IBasketReader(basket_); float = ISupplyControlledERC20(float_); for (uint256 i = 0; i < allowanceTokens_.length; i++) { IERC20 allowanceToken = IERC20(allowanceTokens_[i]); allowanceTokens.push(allowanceToken); } _setupRole(RECOVER_ROLE, governance_); } event Committed(address indexed user, uint256 amount); event Minted(address indexed user, uint256 amount);
12,841,519
[ 1, 13262, 279, 394, 490, 474, 310, 385, 264, 4758, 93, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 262, 6076, 329, 12, 2750, 4758, 93, 1685, 16, 276, 264, 4758, 93, 1685, 397, 385, 654, 3375, 673, 61, 67, 24951, 13, 288, 203, 565, 2583, 12, 75, 1643, 82, 1359, 67, 480, 1758, 12, 20, 3631, 315, 20022, 19, 7170, 1887, 8863, 203, 565, 2583, 12, 2586, 14911, 2582, 67, 480, 1758, 12, 20, 3631, 315, 20022, 19, 7170, 1887, 8863, 203, 565, 2583, 12, 26219, 67, 480, 1758, 12, 20, 3631, 315, 20022, 19, 7170, 1887, 8863, 203, 565, 2583, 12, 5659, 67, 480, 1758, 12, 20, 3631, 315, 20022, 19, 7170, 1887, 8863, 203, 203, 565, 31198, 2582, 273, 6246, 265, 14911, 2582, 12, 2586, 14911, 2582, 67, 1769, 203, 565, 12886, 273, 467, 11324, 2514, 12, 26219, 67, 1769, 203, 565, 1431, 273, 467, 3088, 1283, 3367, 1259, 654, 39, 3462, 12, 5659, 67, 1769, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1699, 1359, 5157, 27799, 2469, 31, 277, 27245, 288, 203, 1377, 467, 654, 39, 3462, 1699, 1359, 1345, 273, 467, 654, 39, 3462, 12, 5965, 1359, 5157, 67, 63, 77, 19226, 203, 203, 1377, 1699, 1359, 5157, 18, 6206, 12, 5965, 1359, 1345, 1769, 203, 565, 289, 203, 203, 565, 389, 8401, 2996, 12, 30724, 2204, 67, 16256, 16, 314, 1643, 82, 1359, 67, 1769, 203, 225, 289, 203, 203, 225, 871, 1286, 7948, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 225, 871, 490, 474, 329, 12, 2867, 8808, 729, 16, 2254, 5034, 3844, 1769, 203, 203, 2 ]
./full_match/5/0x82e5A6Fea932504cBDFf8D53FEAA5e51420d3553/sources/project_/contracts/BaseContracts/Standards/PaymentSplitter.sol
* @dev Getter for the total payees./
function getPayees() view public returns(address[] memory) { return _payees; }
1,899,755
[ 1, 8461, 364, 326, 2078, 8843, 25521, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 528, 25521, 1435, 1476, 1071, 1135, 12, 2867, 8526, 3778, 13, 288, 203, 3639, 327, 389, 10239, 25521, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Contracts/Emeral.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./EmeraldProperties.sol"; import "./EmeraldStates.sol"; contract Emerald { // Product identification and owndership uint sku; // Stock Keeping Unit (SKU) uint upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer address ownerID; // Metamask-Ethereum address of the current owner as the product moves through 8 stages // Product origin information address payable originMinerID; // Metamask-Ethereum address of the Farmer //Mine mine; // Mine information string originMineName; string originMineInformation; string originMineLatitude; string originMineLongitude; uint productID; // Product ID potentially a combination of upc + sku EmeraldStates.State emeraldState;// Emerald state as represented in the enum above // Detailed emerald infomation string scaleInfo; string certifiedProperties; string manofactureInfo; uint marketPrice; // Emerald's market price // Roles applied along the emerald lifecycle address laboratoryID; // Metamask-Ethereum address of the Laboratory address custodianID; // Metamask-Ethereum address of the Custodian address payable manufacturerID; // Metamask-Ethereum address of the Manufacturer (Cutter) address payable customerID; // Metamask-Ethereum address of the Customer constructor() { } function SetExtractionInfo( uint _sku, uint _upc, address payable _originMinerID, string memory _originMineName, string memory _originMineInformation, string memory _originMineLatitude, string memory _originMineLongitude) public { sku = _sku; upc = _upc; ownerID = _originMinerID; originMinerID = _originMinerID; originMineName = _originMineName; originMineInformation = _originMineInformation; originMineLatitude = _originMineLatitude; originMineLongitude = _originMineLongitude; //mine.SetMineInfo(_originMineName, _originMineInformation, _originMineLatitude, _originMineLongitude); productID = sku + _upc; emeraldState = EmeraldStates.State.Mined; marketPrice = 0; laboratoryID = address(0); custodianID = address(0); manufacturerID = address(0); customerID = address(0); } function SetScaleInfo( string memory _scaleInfo) public { scaleInfo = _scaleInfo; } function SetCertifiedInfo(string memory _certifiedProperties) public { certifiedProperties = _certifiedProperties; } function SetManufacturedInfo(string memory _manofactureInfo) public { manofactureInfo = _manofactureInfo; } function SetEmeraldState(EmeraldStates.State _state) public { emeraldState = _state; } function SetOwnerID(address _newOwnerID) public { ownerID = _newOwnerID; } function AuthorizeLab(address _laboratoryID) public { laboratoryID = _laboratoryID; } function AuthorizeCustodian(address _custodianID) public { custodianID = _custodianID; } function SetManufacturerID(address payable _manufacturerID) public { manufacturerID = _manufacturerID; } function SetCustomerID(address payable _customerID) public { customerID = _customerID; } function GetSku() public view returns (uint){ return sku; } function GetUpc() public view returns (uint){ return upc; } function GetProductID() public view returns (uint){ return productID; } function GetOwnerID() public view returns (address){ return ownerID; } function getOriginMinerID() public view returns (address payable){ return originMinerID; } function GetMarketPrice() public view returns (uint){ return marketPrice; } function SetMarketPrice(uint _marketPrice) public { marketPrice = _marketPrice; } function GetCustomerID() public view returns (address payable){ return customerID; } function GetCustodianID() public view returns (address){ return custodianID; } function GetLaboratoryID() public view returns (address){ return laboratoryID; } function getManufacturerID() public view returns (address payable){ return manufacturerID; } function GetEmeraldState() public view returns (EmeraldStates.State){ return emeraldState; } function GetMineName() public view returns (string memory){ return originMineName; } function GetMineInformation() public view returns (string memory){ return originMineInformation; } function GetMineLatitude() public view returns (string memory){ return originMineLatitude; } function GetMineLongitude() public view returns (string memory){ return originMineLongitude; } function GetBasicInfo() public view returns (bytes memory){ return( abi.encode(sku, upc, originMinerID, originMinerID, originMineName, originMineInformation, originMineLatitude, originMineLongitude) ); } function GetDetailedInfo() public view returns (bytes memory){ return( abi.encode(sku, upc, productID, marketPrice, emeraldState, laboratoryID, custodianID, manufacturerID, customerID) ); } }
Emerald's market price
uint marketPrice;
14,049,358
[ 1, 1514, 11612, 72, 1807, 13667, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 13667, 5147, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ 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 ); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); /*function transferFrom(address from, address to, uint256 tokenId) public;*/ /*function safeTransferFrom(address from, address to, uint256 tokenId) public;*/ /*function safeTransferFrom( address from, address to, uint256 tokenId, bytes data ) public;*/ } /** * @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 `safeTransfer`. 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(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address operator, address from, uint256 tokenId, bytes data ) public returns(bytes4); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ /* function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } */ } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721_custom is ERC165, IERC721 { using SafeMath for uint256; using Address for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); 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 Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address owner, address operator ) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId)); // require(to != address(0)); _clearApproval(from, tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } function internal_transferFrom( address _from, address to, uint256 tokenId ) internal { // permissions already checked on price basis // require(to != address(0)); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } //_removeTokenFrom(from, tokenId); if(_ownedTokensCount[_from] > 1) { _ownedTokensCount[_from] = _ownedTokensCount[_from] -1; //.sub(1); // error here // works without .sub()???? } _tokenOwner[tokenId] = address(0); _addTokenTo(to, tokenId); // error here? emit Transfer(_from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ /*function safeTransferFrom( address from, address to, uint256 tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); }*/ /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ /*function safeTransferFrom( address from, address to, uint256 tokenId, bytes _data ) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); }*/ /** * @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) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner( address spender, uint256 tokenId ) internal view returns (bool) { address owner = ownerOf(tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); _addTokenTo(to, tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { _clearApproval(owner, tokenId); _removeTokenFrom(owner, tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 * Note that this function is left internal to make ERC721Enumerable possible, but is not * intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { require(ownerOf(tokenId) == from); _ownedTokensCount[from] = _ownedTokensCount[from].sub(1); _tokenOwner[tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes _data ) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param owner owner of the token * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(address owner, uint256 tokenId) private { require(ownerOf(tokenId) == owner); if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable_custom is ERC165, ERC721_custom, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ /** * @dev Constructor function */ constructor() public { // register the supported interface to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Enumerable); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256) { require(index < balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply()); return _allTokens[index]; } /** * @dev Internal function to add a token ID to the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event. * @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 * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 lastToken = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list _ownedTokensIndex[tokenId] = 0; _ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // 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; } } contract IERC721Metadata is IERC721 { function name() external view returns (string); function symbol() external view returns (string); function tokenURI(uint256 tokenId) external view returns (string); } contract ERC721Metadata_custom is ERC165, ERC721_custom, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor(string name, string symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Metadata); } function name() external view returns (string) { return _name; } function symbol() external view returns (string) { return _symbol; } /* function tokenURI(uint256 tokenId) external view returns (string) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } function _setTokenURI(uint256 tokenId, string uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract ERC721Full_custom is ERC721_custom, ERC721Enumerable_custom, ERC721Metadata_custom { constructor(string name, string symbol) ERC721Metadata_custom(name, symbol) public { } } interface PlanetCryptoCoin_I { function balanceOf(address owner) external returns(uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns(bool); } interface PlanetCryptoUtils_I { function validateLand(address _sender, int256[] plots_lat, int256[] plots_lng) external returns(bool); function validatePurchase(address _sender, uint256 _value, int256[] plots_lat, int256[] plots_lng) external returns(bool); function validateTokenPurchase(address _sender, int256[] plots_lat, int256[] plots_lng) external returns(bool); function validateResale(address _sender, uint256 _value, uint256 _token_id) external returns(bool); function validateLandTakeover(address _sender, uint256 _value, uint256 _token_id) external returns(bool); //UTILS function strConcat(string _a, string _b, string _c, string _d, string _e, string _f) external view returns (string); function strConcat(string _a, string _b, string _c, string _d, string _e) external view returns (string); function strConcat(string _a, string _b, string _c, string _d) external view returns (string); function strConcat(string _a, string _b, string _c) external view returns (string); function strConcat(string _a, string _b) external view returns (string); function int2str(int i) external view returns (string); function uint2str(uint i) external view returns (string); function substring(string str, uint startIndex, uint endIndex) external view returns (string); function utfStringLength(string str) external view returns (uint length); function ceil1(int256 a, int256 m) external view returns (int256 ); function parseInt(string _a, uint _b) external view returns (uint); function roundLatLngFull(uint8 _zoomLvl, int256 __in) external pure returns(int256); } interface PlanetCryptoToken_I { function all_playerObjects(uint256) external returns( address playerAddress, uint256 lastAccess, uint256 totalEmpireScore, uint256 totalLand); function balanceOf(address) external returns(uint256); function getAllPlayerObjectLen() external returns(uint256); function getToken(uint256 _token_id, bool isBasic) external returns( address token_owner, bytes32 name, uint256 orig_value, uint256 current_value, uint256 empire_score, int256[] plots_lat, int256[] plots_lng ); function tax_distributed() external returns(uint256); function tax_fund() external returns(uint256); function taxEarningsAvailable() external returns(uint256); function tokens_rewards_allocated() external returns(uint256); function tokens_rewards_available() external returns(uint256); function total_empire_score() external returns(uint256); function total_land_sold() external returns(uint256); function total_trades() external returns(uint256); function totalSupply() external returns(uint256); function current_plot_price() external returns(uint256); } library Percent { struct percent { uint num; uint den; } function mul(percent storage p, uint a) internal view returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } /* function div(percent storage p, uint a) internal view returns (uint) { return a/p.num*p.den; } function sub(percent storage p, uint a) internal view returns (uint) { uint b = mul(p, a); if (b >= a) return 0; return a - b; } function add(percent storage p, uint a) internal view returns (uint) { return a + mul(p, a); } */ } contract PlanetCryptoToken is ERC721Full_custom{ using Percent for Percent.percent; // EVENTS event referralPaid(address indexed search_to, address to, uint256 amnt, uint256 timestamp); event issueCoinTokens(address indexed searched_to, address to, uint256 amnt, uint256 timestamp); event landPurchased(uint256 indexed search_token_id, address indexed search_buyer, uint256 token_id, address buyer, bytes32 name, int256 center_lat, int256 center_lng, uint256 size, uint256 bought_at, uint256 empire_score, uint256 timestamp); event taxDistributed(uint256 amnt, uint256 total_players, uint256 timestamp); event cardBought( uint256 indexed search_token_id, address indexed search_from, address indexed search_to, uint256 token_id, address from, address to, bytes32 name, uint256 orig_value, uint256 new_value, uint256 empireScore, uint256 newEmpireScore, uint256 timestamp); event cardChange( uint256 indexed search_token_id, address indexed search_owner, uint256 token_id, address owner, uint256 changeType, bytes32 data, uint256 timestamp); // CONTRACT MANAGERS address owner; address devBankAddress; // where marketing funds are sent address tokenBankAddress; // MODIFIERS modifier onlyOwner() { require(msg.sender == owner); _; } modifier validateLand(int256[] plots_lat, int256[] plots_lng) { require(planetCryptoUtils_interface.validateLand(msg.sender, plots_lat, plots_lng) == true, "Some of this land already owned!"); _; } modifier validatePurchase(int256[] plots_lat, int256[] plots_lng) { require(planetCryptoUtils_interface.validatePurchase(msg.sender, msg.value, plots_lat, plots_lng) == true, "Not enough ETH!"); _; } modifier validateTokenPurchase(int256[] plots_lat, int256[] plots_lng) { require(planetCryptoUtils_interface.validateTokenPurchase(msg.sender, plots_lat, plots_lng) == true, "Not enough COINS to buy these plots!"); require(planetCryptoCoin_interface.transferFrom(msg.sender, tokenBankAddress, plots_lat.length) == true, "Token transfer failed"); _; } modifier validateResale(uint256 _token_id) { require(planetCryptoUtils_interface.validateResale(msg.sender, msg.value, _token_id) == true, "Not enough ETH to buy this card!"); _; } modifier updateUsersLastAccess() { uint256 allPlyersIdx = playerAddressToPlayerObjectID[msg.sender]; if(allPlyersIdx == 0){ all_playerObjects.push(player(msg.sender,now,0,0)); playerAddressToPlayerObjectID[msg.sender] = all_playerObjects.length-1; } else { all_playerObjects[allPlyersIdx].lastAccess = now; } _; } // STRUCTS struct plotDetail { bytes32 name; uint256 orig_value; uint256 current_value; uint256 empire_score; int256[] plots_lat; int256[] plots_lng; bytes32 img; } struct plotBasic { int256 lat; int256 lng; } struct player { address playerAddress; uint256 lastAccess; uint256 totalEmpireScore; uint256 totalLand; } // INTERFACES address planetCryptoCoinAddress = 0xA1c8031EF18272d8BfeD22E1b61319D6d9d2881B; // mainnet //address planetCryptoCoinAddress = 0xe1418a2546fe0c35653c89b354978bd1772bb431; // ropsten PlanetCryptoCoin_I internal planetCryptoCoin_interface; address planetCryptoUtilsAddress = 0x40089b9f4d5eb36d62548133f32e52b14fa54c52; // mainnet //address planetCryptoUtilsAddress = 0x7e3d67c3b1469f152f38367c06463917412c9c19; // ropsten PlanetCryptoUtils_I internal planetCryptoUtils_interface; // settings Percent.percent private m_newPlot_devPercent = Percent.percent(75,100); //75/100*100% = 75% Percent.percent private m_newPlot_taxPercent = Percent.percent(25,100); //25% Percent.percent private m_resalePlot_devPercent = Percent.percent(10,100); // 10% Percent.percent private m_resalePlot_taxPercent = Percent.percent(10,100); // 10% Percent.percent private m_resalePlot_ownerPercent = Percent.percent(80,100); // 80% //Percent.percent private m_takeoverPlot_devPercent = Percent.percent(10,100); // 10% //Percent.percent private m_takeoverPlot_taxPercent = Percent.percent(10,100); // 10% //Percent.percent private m_takeoverPlot_ownerPercent = Percent.percent(80,100); // 80% Percent.percent private m_refPercent = Percent.percent(5,100); // 5% referral Percent.percent private m_empireScoreMultiplier = Percent.percent(150,100); // 150% Percent.percent private m_resaleMultipler = Percent.percent(200,100); // 200%; uint256 public devHoldings = 0; // holds dev funds in cases where the instant transfer fails mapping(address => uint256) internal playersFundsOwed; // add in limit of land plots before tokens stop being distributed uint256 public tokens_rewards_available; uint256 public tokens_rewards_allocated; // add in spend amount required to earn tokens uint256 public min_plots_purchase_for_token_reward = 10; uint256 public plots_token_reward_divisor = 10; // GAME SETTINGS uint256 public current_plot_price = 20000000000000000; uint256 public price_update_amount = 2000000000000; uint256 public cardChangeNameCost = 50000000000000000; uint256 public cardImageCost = 100000000000000000; uint256 public current_plot_empire_score = 100; string public baseURI = 'https://planetcrypto.app/api/token/'; uint256 public tax_fund = 0; uint256 public tax_distributed = 0; // GAME STATS uint256 public tokenIDCount = 0; bool public game_started = false; uint256 public total_land_sold = 0; uint256 public total_trades = 0; uint256 internal tax_carried_forward = 0; uint256 public total_empire_score; player[] public all_playerObjects; mapping(address => uint256) internal playerAddressToPlayerObjectID; plotDetail[] plotDetails; mapping(uint256 => uint256) internal tokenIDplotdetailsIndexId; // e.g. tokenIDplotdetailsIndexId shows us the index of the detail obj for each token mapping(int256 => mapping(int256 => uint256)) internal latlngTokenID_grids; //mapping(uint256 => plotBasic[]) internal tokenIDlatlngLookup; // To allow burn lookups //mapping(uint256 => int256[]) internal tokenIDlatlngLookup_lat; // To allow burn lookups //mapping(uint256 => int256[]) internal tokenIDlatlngLookup_lng; // To allow burn lookups mapping(uint8 => mapping(int256 => mapping(int256 => uint256))) internal latlngTokenID_zoomAll; mapping(uint8 => mapping(uint256 => plotBasic[])) internal tokenIDlatlngLookup_zoomAll; PlanetCryptoToken internal planetCryptoToken_I = PlanetCryptoToken(0x1806B3527C18Fb532C46405f6f014C1F381b499A); //PlanetCryptoToken internal planetCryptoToken_I = PlanetCryptoToken(0xd13faafc8e8b3f1acc6b84c8df845992e56dcd5b); constructor() ERC721Full_custom("PlanetCrypto", "PLANET") public { owner = msg.sender; tokenBankAddress = owner; devBankAddress = owner; planetCryptoCoin_interface = PlanetCryptoCoin_I(planetCryptoCoinAddress); planetCryptoUtils_interface = PlanetCryptoUtils_I(planetCryptoUtilsAddress); all_playerObjects.push(player(address(0x0),0,0,0)); playerAddressToPlayerObjectID[address(0x0)] = 0; total_trades = planetCryptoToken_I.total_trades(); total_land_sold = planetCryptoToken_I.total_land_sold(); total_empire_score = planetCryptoToken_I.total_empire_score(); tokens_rewards_available = planetCryptoToken_I.tokens_rewards_available(); tokens_rewards_allocated = planetCryptoToken_I.tokens_rewards_allocated(); tax_distributed = planetCryptoToken_I.tax_distributed(); tax_fund = 0; current_plot_price = planetCryptoToken_I.current_plot_price(); } function initPlayers(uint32 _start, uint32 _end) public onlyOwner { require(game_started == false); for(uint32 c=_start; c< _end+1; c++){ transferPlayer(uint256(c)); } } function transferPlayer(uint256 _player_id) internal { (address _playerAddress, uint256 _uint1, uint256 _uint2, uint256 _uint3) = planetCryptoToken_I.all_playerObjects(_player_id); all_playerObjects.push( player( _playerAddress, _uint1, _uint2, _uint3 ) ); playerAddressToPlayerObjectID[_playerAddress] = all_playerObjects.length-1; } function transferTokens(uint256 _start, uint256 _end) public onlyOwner { require(game_started == false); for(uint256 c=_start; c< _end+1; c++) { ( address _playerAddress, bytes32 name, uint256 orig_value, uint256 current_value, uint256 empire_score, int256[] memory plots_lat, int256[] memory plots_lng ) = planetCryptoToken_I.getToken(c, false); transferCards(c, _playerAddress, name, orig_value, current_value, empire_score, plots_lat, plots_lng); } } function transferCards( uint256 _cardID, address token_owner, bytes32 name, uint256 orig_value, uint256 current_value, uint256 empire_score, int256[] memory plots_lat, int256[] memory plots_lng ) internal { _mint(token_owner, _cardID); tokenIDCount = tokenIDCount + 1; plotDetails.push(plotDetail( name, orig_value, current_value, empire_score, plots_lat, plots_lng, '' )); tokenIDplotdetailsIndexId[_cardID] = plotDetails.length-1; setupPlotOwnership(_cardID, plots_lat, plots_lng); } function tokenURI(uint256 tokenId) external view returns (string) { require(_exists(tokenId)); return planetCryptoUtils_interface.strConcat(baseURI, planetCryptoUtils_interface.uint2str(tokenId)); } function getToken(uint256 _tokenId, bool isBasic) public view returns( address token_owner, bytes32 name, uint256 orig_value, uint256 current_value, uint256 empire_score, int256[] plots_lat, int256[] plots_lng ) { token_owner = ownerOf(_tokenId); plotDetail memory _plotDetail = plotDetails[tokenIDplotdetailsIndexId[_tokenId]]; name = _plotDetail.name; empire_score = _plotDetail.empire_score; orig_value = _plotDetail.orig_value; current_value = _plotDetail.current_value; if(!isBasic){ plots_lat = _plotDetail.plots_lat; plots_lng = _plotDetail.plots_lng; } } function getTokenEnhanced(uint256 _tokenId, bool isBasic) public view returns( address token_owner, bytes32 name, bytes32 img, uint256 orig_value, uint256 current_value, uint256 empire_score, int256[] plots_lat, int256[] plots_lng ) { token_owner = ownerOf(_tokenId); plotDetail memory _plotDetail = plotDetails[tokenIDplotdetailsIndexId[_tokenId]]; name = _plotDetail.name; img = _plotDetail.img; empire_score = _plotDetail.empire_score; orig_value = _plotDetail.orig_value; current_value = _plotDetail.current_value; if(!isBasic){ plots_lat = _plotDetail.plots_lat; plots_lng = _plotDetail.plots_lng; } } function taxEarningsAvailable() public view returns(uint256) { return playersFundsOwed[msg.sender]; } function withdrawTaxEarning() public { uint256 taxEarnings = playersFundsOwed[msg.sender]; playersFundsOwed[msg.sender] = 0; tax_fund = tax_fund.sub(taxEarnings); if(!msg.sender.send(taxEarnings)) { playersFundsOwed[msg.sender] = playersFundsOwed[msg.sender] + taxEarnings; tax_fund = tax_fund.add(taxEarnings); } } function buyLandWithTokens(bytes32 _name, int256[] _plots_lat, int256[] _plots_lng) validateTokenPurchase(_plots_lat, _plots_lng) validateLand(_plots_lat, _plots_lng) updateUsersLastAccess() public { require(_name.length > 4); processPurchase(_name, _plots_lat, _plots_lng); game_started = true; } function buyLand(bytes32 _name, int256[] _plots_lat, int256[] _plots_lng, address _referrer ) validatePurchase(_plots_lat, _plots_lng) validateLand(_plots_lat, _plots_lng) updateUsersLastAccess() public payable { require(_name.length > 4); // split payment uint256 _runningTotal = msg.value; _runningTotal = _runningTotal.sub(processReferer(_referrer)); tax_fund = tax_fund.add(m_newPlot_taxPercent.mul(_runningTotal)); processDevPayment(_runningTotal, m_newPlot_devPercent); processPurchase(_name, _plots_lat, _plots_lng); calcPlayerDivs(m_newPlot_taxPercent.mul(_runningTotal)); game_started = true; if(_plots_lat.length >= min_plots_purchase_for_token_reward && tokens_rewards_available > 0) { uint256 _token_rewards = _plots_lat.length / plots_token_reward_divisor; if(_token_rewards > tokens_rewards_available) _token_rewards = tokens_rewards_available; planetCryptoCoin_interface.transfer(msg.sender, _token_rewards); emit issueCoinTokens(msg.sender, msg.sender, _token_rewards, now); tokens_rewards_allocated = tokens_rewards_allocated + _token_rewards; tokens_rewards_available = tokens_rewards_available - _token_rewards; } } function processReferer(address _referrer) internal returns(uint256) { uint256 _referrerAmnt = 0; if(_referrer != msg.sender && _referrer != address(0)) { _referrerAmnt = m_refPercent.mul(msg.value); if(_referrer.send(_referrerAmnt)) { emit referralPaid(_referrer, _referrer, _referrerAmnt, now); //_runningTotal = _runningTotal.sub(_referrerAmnt); } } return _referrerAmnt; } function processDevPayment(uint256 _runningTotal, Percent.percent storage _percent) internal { if(!devBankAddress.send(_percent.mul(_runningTotal))){ devHoldings = devHoldings.add(_percent.mul(_runningTotal)); } } // TO BE TESTED function buyCard(uint256 _token_id, address _referrer) updateUsersLastAccess() public payable { //validateResale(_token_id) if(planetCryptoUtils_interface.validateResale(msg.sender, msg.value, _token_id) == false) { if(planetCryptoUtils_interface.validateLandTakeover(msg.sender, msg.value, _token_id) == false) { revert("Cannot Buy this Card Yet!"); } } processBuyCard(_token_id, _referrer); } function processBuyCard(uint256 _token_id, address _referrer) internal { // split payment uint256 _runningTotal = msg.value; _runningTotal = _runningTotal.sub(processReferer(_referrer)); tax_fund = tax_fund.add(m_resalePlot_taxPercent.mul(_runningTotal)); processDevPayment(_runningTotal, m_resalePlot_devPercent); address from = ownerOf(_token_id); if(!from.send(m_resalePlot_ownerPercent.mul(_runningTotal))) { playersFundsOwed[from] = playersFundsOwed[from].add(m_resalePlot_ownerPercent.mul(_runningTotal)); } process_swap(from,msg.sender,_token_id); internal_transferFrom(from, msg.sender, _token_id); //plotDetail memory _plotDetail = plotDetails[tokenIDplotdetailsIndexId[_token_id]]; uint256 _empireScore = plotDetails[tokenIDplotdetailsIndexId[_token_id]].empire_score; // apply bonus when card is bought through site uint256 _newEmpireScore = m_empireScoreMultiplier.mul(_empireScore); uint256 _origValue = plotDetails[tokenIDplotdetailsIndexId[_token_id]].current_value; all_playerObjects[playerAddressToPlayerObjectID[msg.sender]].totalEmpireScore = all_playerObjects[playerAddressToPlayerObjectID[msg.sender]].totalEmpireScore + (_newEmpireScore - _empireScore); plotDetails[tokenIDplotdetailsIndexId[_token_id]].empire_score = _newEmpireScore; total_empire_score = total_empire_score + (_newEmpireScore - _empireScore); plotDetails[tokenIDplotdetailsIndexId[_token_id]].current_value = m_resaleMultipler.mul(plotDetails[tokenIDplotdetailsIndexId[_token_id]].current_value); total_trades = total_trades + 1; calcPlayerDivs(m_resalePlot_taxPercent.mul(_runningTotal)); plotDetail memory _plot =plotDetails[tokenIDplotdetailsIndexId[_token_id]]; emit cardBought(_token_id, from, ownerOf(_token_id), _token_id, from, ownerOf(_token_id), _plot.name, _origValue, _plot.current_value, _empireScore, _plot.empire_score, now); } function processPurchase(bytes32 _name, int256[] _plots_lat, int256[] _plots_lng) internal { tokenIDCount = tokenIDCount + 1; //uint256 _token_id = tokenIDCount; //totalSupply().add(1); _mint(msg.sender, tokenIDCount); plotDetails.push(plotDetail( _name, current_plot_price * _plots_lat.length, current_plot_price * _plots_lat.length, current_plot_empire_score * _plots_lng.length, _plots_lat, _plots_lng, '' )); tokenIDplotdetailsIndexId[tokenIDCount] = plotDetails.length-1; setupPlotOwnership(tokenIDCount, _plots_lat, _plots_lng); uint256 _playerObject_idx = playerAddressToPlayerObjectID[msg.sender]; all_playerObjects[_playerObject_idx].totalEmpireScore = all_playerObjects[_playerObject_idx].totalEmpireScore + (current_plot_empire_score * _plots_lng.length); total_empire_score = total_empire_score + (current_plot_empire_score * _plots_lng.length); all_playerObjects[_playerObject_idx].totalLand = all_playerObjects[_playerObject_idx].totalLand + _plots_lat.length; emit landPurchased( tokenIDCount, msg.sender, tokenIDCount, msg.sender, _name, _plots_lat[0], _plots_lng[0], _plots_lat.length, current_plot_price, (current_plot_empire_score * _plots_lng.length), now); current_plot_price = current_plot_price + (price_update_amount * _plots_lat.length); total_land_sold = total_land_sold + _plots_lat.length; } function updateCardDetail(uint256 _token_id, uint256 _updateType, bytes32 _data) public payable { require(msg.sender == ownerOf(_token_id)); if(_updateType == 1) { // CardImage require(msg.value == cardImageCost); plotDetails[ tokenIDplotdetailsIndexId[_token_id] ].img = _data; } if(_updateType == 2) { // Name change require(_data.length > 4); require(msg.value == cardChangeNameCost); plotDetails[ tokenIDplotdetailsIndexId[_token_id] ].name = _data; } processDevPayment(msg.value,m_newPlot_devPercent); /* if(!devBankAddress.send(msg.value)){ devHoldings = devHoldings.add(msg.value); } */ emit cardChange( _token_id, msg.sender, _token_id, msg.sender, _updateType, _data, now); } function calcPlayerDivs(uint256 _value) internal { // total up amount split so we can emit it //if(totalSupply() > 1) { if(game_started) { uint256 _totalDivs = 0; uint256 _totalPlayers = 0; uint256 _taxToDivide = _value + tax_carried_forward; // ignore player 0 for(uint256 c=1; c< all_playerObjects.length; c++) { // allow for 0.0001 % = * 10000 uint256 _playersPercent = (all_playerObjects[c].totalEmpireScore*10000000 / total_empire_score * 10000000) / 10000000; uint256 _playerShare = _taxToDivide / 10000000 * _playersPercent; if(_playerShare > 0) { playersFundsOwed[all_playerObjects[c].playerAddress] = playersFundsOwed[all_playerObjects[c].playerAddress].add(_playerShare); tax_distributed = tax_distributed.add(_playerShare); _totalDivs = _totalDivs + _playerShare; _totalPlayers = _totalPlayers + 1; } } tax_carried_forward = 0; emit taxDistributed(_totalDivs, _totalPlayers, now); } else { // first land purchase - no divs this time, carried forward tax_carried_forward = tax_carried_forward + _value; } } function setupPlotOwnership(uint256 _token_id, int256[] _plots_lat, int256[] _plots_lng) internal { for(uint256 c=0;c< _plots_lat.length;c++) { latlngTokenID_grids[_plots_lat[c]] [_plots_lng[c]] = _token_id; } for(uint8 zoomC = 1; c < 5; c++) { setupZoomLvl(zoomC,_plots_lat[0], _plots_lng[0], _token_id); // correct rounding / 10 on way out } } function setupZoomLvl(uint8 zoom, int256 lat, int256 lng, uint256 _token_id) internal { lat = planetCryptoUtils_interface.roundLatLngFull(zoom, lat); lng = planetCryptoUtils_interface.roundLatLngFull(zoom, lng); latlngTokenID_zoomAll[zoom][lat][lng] = _token_id; tokenIDlatlngLookup_zoomAll[zoom][_token_id].push( plotBasic(lat,lng) ); } function getAllPlayerObjectLen() public view returns(uint256){ return all_playerObjects.length; } function queryMap(uint8 zoom, int256[] lat_rows, int256[] lng_columns) public view returns(string _outStr) { for(uint256 y=0; y< lat_rows.length; y++) { for(uint256 x=0; x< lng_columns.length; x++) { if(zoom == 0){ if(latlngTokenID_grids[lat_rows[y]][lng_columns[x]] > 0){ _outStr = planetCryptoUtils_interface.strConcat( _outStr, '[', planetCryptoUtils_interface.int2str(lat_rows[y]) , ':', planetCryptoUtils_interface.int2str(lng_columns[x]) ); _outStr = planetCryptoUtils_interface.strConcat(_outStr, ':', planetCryptoUtils_interface.uint2str(latlngTokenID_grids[lat_rows[y]][lng_columns[x]]), ']'); } } else { //_out[c] = latlngTokenID_zoomAll[zoom][lat_rows[y]][lng_columns[x]]; if(latlngTokenID_zoomAll[zoom][lat_rows[y]][lng_columns[x]] > 0){ _outStr = planetCryptoUtils_interface.strConcat(_outStr, '[', planetCryptoUtils_interface.int2str(lat_rows[y]) , ':', planetCryptoUtils_interface.int2str(lng_columns[x]) ); _outStr = planetCryptoUtils_interface.strConcat(_outStr, ':', planetCryptoUtils_interface.uint2str(latlngTokenID_zoomAll[zoom][lat_rows[y]][lng_columns[x]]), ']'); } } //c = c+1; } } //return _out; } // used in utils function queryPlotExists(uint8 zoom, int256[] lat_rows, int256[] lng_columns) public view returns(bool) { for(uint256 y=0; y< lat_rows.length; y++) { for(uint256 x=0; x< lng_columns.length; x++) { if(zoom == 0){ if(latlngTokenID_grids[lat_rows[y]][lng_columns[x]] > 0){ return true; } } else { if(latlngTokenID_zoomAll[zoom][lat_rows[y]][lng_columns[x]] > 0){ return true; } } } } return false; } // ERC721 overrides function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } function transferFrom(address from, address to, uint256 tokenId) public { // check permission on the from address first require(_isApprovedOrOwner(msg.sender, tokenId)); require(to != address(0)); process_swap(from,to,tokenId); super.transferFrom(from, to, tokenId); } function process_swap(address from, address to, uint256 tokenId) internal { // remove the empire score & total land owned... uint256 _empireScore; uint256 _size; //plotDetail memory _plotDetail = plotDetails[tokenIDplotdetailsIndexId[tokenId]]; _empireScore = plotDetails[tokenIDplotdetailsIndexId[tokenId]].empire_score; _size = plotDetails[tokenIDplotdetailsIndexId[tokenId]].plots_lat.length; uint256 _playerObject_idx = playerAddressToPlayerObjectID[from]; all_playerObjects[_playerObject_idx].totalEmpireScore = all_playerObjects[_playerObject_idx].totalEmpireScore - _empireScore; all_playerObjects[_playerObject_idx].totalLand = all_playerObjects[_playerObject_idx].totalLand - _size; // and increment on the other side... _playerObject_idx = playerAddressToPlayerObjectID[to]; // ensure the player is setup first... if(_playerObject_idx == 0){ all_playerObjects.push(player(to,now,0,0)); playerAddressToPlayerObjectID[to] = all_playerObjects.length-1; _playerObject_idx = all_playerObjects.length-1; } all_playerObjects[_playerObject_idx].totalEmpireScore = all_playerObjects[_playerObject_idx].totalEmpireScore + _empireScore; all_playerObjects[_playerObject_idx].totalLand = all_playerObjects[_playerObject_idx].totalLand + _size; } // PRIVATE METHODS function p_update_action(uint256 _type, address _address, uint256 _val, string _strVal) public onlyOwner { if(_type == 0){ owner = _address; } if(_type == 1){ tokenBankAddress = _address; } if(_type == 2) { devBankAddress = _address; } if(_type == 3) { cardChangeNameCost = _val; } if(_type == 4) { cardImageCost = _val; } if(_type == 5) { baseURI = _strVal; } if(_type == 6) { price_update_amount = _val; } if(_type == 7) { current_plot_empire_score = _val; } if(_type == 8) { planetCryptoCoinAddress = _address; if(address(planetCryptoCoinAddress) != address(0)){ planetCryptoCoin_interface = PlanetCryptoCoin_I(planetCryptoCoinAddress); } } if(_type ==9) { planetCryptoUtilsAddress = _address; if(address(planetCryptoUtilsAddress) != address(0)){ planetCryptoUtils_interface = PlanetCryptoUtils_I(planetCryptoUtilsAddress); } } if(_type == 10) { m_newPlot_devPercent = Percent.percent(_val,100); } if(_type == 11) { m_newPlot_taxPercent = Percent.percent(_val,100); } if(_type == 12) { m_resalePlot_devPercent = Percent.percent(_val,100); } if(_type == 13) { m_resalePlot_taxPercent = Percent.percent(_val,100); } if(_type == 14) { m_resalePlot_ownerPercent = Percent.percent(_val,100); } if(_type == 15) { m_refPercent = Percent.percent(_val,100); } if(_type == 16) { m_empireScoreMultiplier = Percent.percent(_val, 100); } if(_type == 17) { m_resaleMultipler = Percent.percent(_val, 100); } if(_type == 18) { tokens_rewards_available = _val; } if(_type == 19) { tokens_rewards_allocated = _val; } if(_type == 20) { // clear card image plotDetails[ tokenIDplotdetailsIndexId[_val] ].img = ''; emit cardChange( _val, msg.sender, _val, msg.sender, 1, '', now); } if(_type == 99) { // burnToken address _token_owner = ownerOf(_val); //internal_transferFrom(_token_owner, 0x0000000000000000000000000000000000000000, _val); processBurn(_token_owner, _val); } } function burn(uint256 _token_id) public { require(msg.sender == ownerOf(_token_id)); uint256 _cardSize = plotDetails[tokenIDplotdetailsIndexId[_token_id]].plots_lat.length; //super.transferFrom(msg.sender, 0x0000000000000000000000000000000000000000, _token_id); processBurn(msg.sender, _token_id); // allocate PlanetCOIN tokens to user... planetCryptoCoin_interface.transfer(msg.sender, _cardSize); } function processBurn(address _token_owner, uint256 _val) internal { _burn(_token_owner, _val); // remove the empire score & total land owned... uint256 _empireScore; uint256 _size; _empireScore = plotDetails[tokenIDplotdetailsIndexId[_val]].empire_score; _size = plotDetails[tokenIDplotdetailsIndexId[_val]].plots_lat.length; total_land_sold = total_land_sold - _size; total_empire_score = total_empire_score - _empireScore; uint256 _playerObject_idx = playerAddressToPlayerObjectID[_token_owner]; all_playerObjects[_playerObject_idx].totalEmpireScore = all_playerObjects[_playerObject_idx].totalEmpireScore - _empireScore; all_playerObjects[_playerObject_idx].totalLand = all_playerObjects[_playerObject_idx].totalLand - _size; for(uint256 c=0;c < plotDetails[tokenIDplotdetailsIndexId[_val]].plots_lat.length; c++) { latlngTokenID_grids[ //tokenIDlatlngLookup_lat[_val][c] plotDetails[tokenIDplotdetailsIndexId[_val]].plots_lat[c] ] [ //tokenIDlatlngLookup_lng[_val][c] plotDetails[tokenIDplotdetailsIndexId[_val]].plots_lng[c] ] = 0; } for(uint8 zoom=1; zoom < 5; zoom++) { plotBasic[] storage _plotBasicList = tokenIDlatlngLookup_zoomAll[zoom][_val]; for(c=0; c< _plotBasicList.length; c++) { delete latlngTokenID_zoomAll[zoom][ _plotBasicList[c].lat ][ _plotBasicList[c].lng ]; delete _plotBasicList[c]; } } delete plotDetails[tokenIDplotdetailsIndexId[_val]]; tokenIDplotdetailsIndexId[_val] = 0; //delete tokenIDplotdetailsIndexId[_val]; } function p_withdrawDevHoldings() public { require(msg.sender == devBankAddress); uint256 _t = devHoldings; devHoldings = 0; if(!devBankAddress.send(devHoldings)){ devHoldings = _t; } } function m() public { } }
plotDetail memory _plotDetail = plotDetails[tokenIDplotdetailsIndexId[_token_id]];
uint256 _newEmpireScore = m_empireScoreMultiplier.mul(_empireScore);
5,342,172
[ 1, 4032, 6109, 3778, 389, 4032, 6109, 273, 3207, 3790, 63, 2316, 734, 4032, 6395, 1016, 548, 63, 67, 2316, 67, 350, 13563, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 389, 2704, 41, 1291, 577, 7295, 273, 312, 67, 30752, 577, 7295, 23365, 18, 16411, 24899, 30752, 577, 7295, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0xF12058908aF8aE635484789874E5146998864277/sources/project_/contracts/token/superfluid/SuperToken.sol
unused - place holder
function selfMint( address account, uint256 amount, bytes memory userData ) external override onlySelf { revert(); }
16,833,938
[ 1, 14375, 300, 3166, 10438, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 365, 49, 474, 12, 203, 202, 202, 2867, 2236, 16, 203, 202, 202, 11890, 5034, 3844, 16, 203, 202, 202, 3890, 3778, 13530, 203, 202, 13, 3903, 3849, 1338, 10084, 288, 203, 202, 202, 266, 1097, 5621, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xeB40E25AF8F5F22Bb201f53971480beA0094Cd65/sources/src/v0.8/functions/dev/1_0_0/accessControl/TermsOfServiceAllowList.sol
@inheritdoc ITermsOfServiceAllowList
function isBlockedSender(address sender) external view override returns (bool) { if (!s_config.enabled) { return false; } return s_blockedSenders[sender]; }
4,322,658
[ 1, 36, 10093, 467, 11673, 951, 1179, 7009, 682, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 353, 23722, 12021, 12, 2867, 5793, 13, 3903, 1476, 3849, 1135, 261, 6430, 13, 288, 203, 565, 309, 16051, 87, 67, 1425, 18, 5745, 13, 288, 203, 1377, 327, 629, 31, 203, 565, 289, 203, 565, 327, 272, 67, 23156, 3826, 414, 63, 15330, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; /** * @title SafeMath by OpenZeppelin * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract ICO { using SafeMath for uint256; //This ico have 3 stages enum State { Ongoin, SoftCap, Successful } //public variables State public state = State.Ongoin; //Set initial stage uint256 public startTime = now; //block-time when it was deployed uint256 public delay; //List of prices, as both, eth and token have 18 decimal, its a direct factor uint[2] public tablePrices = [ 2500, //for first 10million tokens 2000 ]; uint256 public SoftCap = 40000000 * (10 ** 18); //40 million tokens uint256 public HardCap = 80000000 * (10 ** 18); //80 million tokens uint256 public totalRaised; //eth in wei uint256 public totalDistributed; //tokens uint256 public ICOdeadline = startTime.add(21 days);//21 days deadline uint256 public completedAt; uint256 public closedAt; token public tokenReward; address public creator; address public beneficiary; string public campaignUrl; uint8 constant version = 1; //events for log event LogFundingReceived(address _addr, uint _amount, uint _currentTotal); event LogBeneficiaryPaid(address _beneficiaryAddress); event LogFundingSuccessful(uint _totalRaised); event LogFunderInitialized( address _creator, address _beneficiary, string _url, uint256 _ICOdeadline); event LogContributorsPayout(address _addr, uint _amount); modifier notFinished() { require(state != State.Successful); _; } /** * @notice ICO constructor * @param _campaignUrl is the ICO _url * @param _addressOfTokenUsedAsReward is the token totalDistributed */ function ICO (string _campaignUrl, token _addressOfTokenUsedAsReward, uint256 _delay) public { creator = msg.sender; beneficiary = msg.sender; campaignUrl = _campaignUrl; tokenReward = token(_addressOfTokenUsedAsReward); delay = startTime.add(_delay * 1 hours); LogFunderInitialized( creator, beneficiary, campaignUrl, ICOdeadline); } /** * @notice contribution handler */ function contribute() public notFinished payable { require(now > delay); uint tokenBought; totalRaised = totalRaised.add(msg.value); if(totalDistributed < 10000000 * (10 ** 18)){ //if on the first 10M tokenBought = msg.value.mul(tablePrices[0]); } else { tokenBought = msg.value.mul(tablePrices[1]); } totalDistributed = totalDistributed.add(tokenBought); tokenReward.transfer(msg.sender, tokenBought); LogFundingReceived(msg.sender, msg.value, totalRaised); LogContributorsPayout(msg.sender, tokenBought); checkIfFundingCompleteOrExpired(); } /** * @notice check status */ function checkIfFundingCompleteOrExpired() public { if(now < ICOdeadline && state!=State.Successful){ //if we are on ICO period and its not Successful if(state == State.Ongoin && totalRaised >= SoftCap){ //if we are Ongoin and we pass the SoftCap state = State.SoftCap; //We are on SoftCap state completedAt = now; //ICO is complete and will finish in 24h } else if (state == State.SoftCap && now > completedAt.add(24 hours)){ //if we are on SoftCap state and 24hrs have passed state == State.Successful; //the ico becomes Successful closedAt = now; //we finish now LogFundingSuccessful(totalRaised); //we log the finish finished(); //and execute closure } } else if(now > ICOdeadline && state!=State.Successful ) { //if we reach ico deadline and its not Successful yet state = State.Successful; //ico becomes Successful if(completedAt == 0){ //if not completed previously completedAt = now; //we complete now } closedAt = now; //we finish now LogFundingSuccessful(totalRaised); //we log the finish finished(); //and execute closure } } function payOut() public { require(msg.sender == beneficiary); require(beneficiary.send(this.balance)); LogBeneficiaryPaid(beneficiary); } /** * @notice closure handler */ function finished() public { //When finished eth are transfered to beneficiary require(state == State.Successful); uint256 remanent = tokenReward.balanceOf(this); require(beneficiary.send(this.balance)); tokenReward.transfer(beneficiary,remanent); LogBeneficiaryPaid(beneficiary); LogContributorsPayout(beneficiary, remanent); } function () public payable { contribute(); } }
ICO is complete and will finish in 24h
completedAt = now;
12,809,140
[ 1, 2871, 51, 353, 3912, 471, 903, 4076, 316, 4248, 76, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 5951, 861, 273, 2037, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) 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/ERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) 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 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 {} } // File: contract-972772ddd8.sol pragma solidity ^0.8.2; contract Tangelo is ERC20, Pausable, Ownable { bool isPublic = false; mapping (address => bool) whitelist; constructor() ERC20("Tangelo", "TGO") { whitelist[msg.sender] = true; _mint(msg.sender, 1000000 * 10 ** decimals()); } modifier whitelisted(address _address) { if (!isPublic) { require(whitelist[_address]); } _; } function setWhitelistStatus(address _address, bool status) public onlyOwner { whitelist[_address] = status; } function setPublic(bool _isPublic) public onlyOwner { isPublic = _isPublic; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused whitelisted(to) override { super._beforeTokenTransfer(from, to, amount); } }
File: contract-972772ddd8.sol
contract Tangelo is ERC20, Pausable, Ownable { bool isPublic = false; mapping (address => bool) whitelist; function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.2; constructor() ERC20("Tangelo", "TGO") { whitelist[msg.sender] = true; _mint(msg.sender, 1000000 * 10 ** decimals()); } modifier whitelisted(address _address) { if (!isPublic) { require(whitelist[_address]); } _; } modifier whitelisted(address _address) { if (!isPublic) { require(whitelist[_address]); } _; } function setWhitelistStatus(address _address, bool status) public onlyOwner { whitelist[_address] = status; } function setPublic(bool _isPublic) public onlyOwner { isPublic = _isPublic; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused whitelisted(to) override { super._beforeTokenTransfer(from, to, amount); } }
6,845,014
[ 1, 812, 30, 6835, 17, 29, 9060, 4700, 22, 449, 72, 28, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 399, 539, 24214, 353, 4232, 39, 3462, 16, 21800, 16665, 16, 14223, 6914, 288, 203, 565, 1426, 19620, 273, 629, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 10734, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 22, 31, 203, 203, 203, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 56, 539, 24214, 3113, 315, 56, 16387, 7923, 288, 203, 3639, 10734, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 15088, 380, 1728, 2826, 15105, 10663, 203, 565, 289, 203, 203, 565, 9606, 26944, 12, 2867, 389, 2867, 13, 288, 203, 3639, 309, 16051, 291, 4782, 13, 288, 203, 5411, 2583, 12, 20409, 63, 67, 2867, 19226, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 26944, 12, 2867, 389, 2867, 13, 288, 203, 3639, 309, 16051, 291, 4782, 13, 288, 203, 5411, 2583, 12, 20409, 63, 67, 2867, 19226, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 444, 18927, 1482, 12, 2867, 389, 2867, 16, 1426, 1267, 13, 1071, 1338, 5541, 288, 203, 3639, 10734, 63, 67, 2867, 65, 273, 1267, 31, 203, 2 ]
/* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { RebalancingLibrary } from "../../lib/RebalancingLibrary.sol"; import { RebalancingSetState } from "./RebalancingSetState.sol"; /** * @title RebalancingBid * @author Set Protocol * * Implementation of Rebalancing Set Token V2 bidding-related functionality. */ contract RebalancingBid is RebalancingSetState { using SafeMath for uint256; /* ============ Internal Functions ============ */ /* * Validates conditions to retrieve a Bid Price: * - State is Rebalance * - Quanity is greater than zero * * @param _quantity The amount of currentSet to be rebalanced */ function validateGetBidPrice( uint256 _quantity ) internal view { validateRebalanceStateIs(RebalancingLibrary.State.Rebalance); require( _quantity > 0, "Bid not > 0" ); } /* * Validations for placeBid: * - Module is sender * - getBidPrice validations * * @param _quantity The amount of currentSet to be rebalanced */ function validatePlaceBid( uint256 _quantity ) internal view { validateCallerIsModule(); validateGetBidPrice(_quantity); } /* * If a successful bid has been made, flip the hasBidded boolean. */ function updateHasBiddedIfNecessary() internal { if (!hasBidded) { hasBidded = true; } } }
If a successful bid has been made, flip the hasBidded boolean./
function updateHasBiddedIfNecessary() internal { if (!hasBidded) { hasBidded = true; } }
6,343,007
[ 1, 2047, 279, 6873, 9949, 711, 2118, 7165, 16, 9668, 326, 711, 17763, 785, 1250, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 5582, 17763, 785, 26034, 1435, 203, 3639, 2713, 203, 565, 288, 203, 3639, 309, 16051, 5332, 17763, 785, 13, 288, 203, 5411, 711, 17763, 785, 273, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.17; // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } /* * SPDX-License-Identifier: MIT */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); } /* * SPDX-License-Identifier: MIT */ interface IArbitrator { /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external; /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Subject associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount); /** * @dev Tell the payments recipient address * @return Address of the payments recipient module */ function getPaymentsRecipient() external view returns (address); } /* * SPDX-License-Identifier: MIT */ /** * @dev The Arbitrable instances actually don't require to follow any specific interface. * Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances. */ contract IArbitrable { /** * @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator * @param arbitrator IArbitrator instance ruling the dispute * @param disputeId Identification number of the dispute being ruled by the arbitrator * @param ruling Ruling given by the arbitrator */ event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } contract ACL { string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE"; string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN"; string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT"; enum BulkOp { Grant, Revoke, Freeze } address internal constant FREEZE_FLAG = address(1); address internal constant ANY_ADDR = address(-1); // List of all roles assigned to different addresses mapping (bytes32 => mapping (address => bool)) public roles; event Granted(bytes32 indexed id, address indexed who); event Revoked(bytes32 indexed id, address indexed who); event Frozen(bytes32 indexed id); /** * @dev Tell whether an address has a role assigned * @param _who Address being queried * @param _id ID of the role being checked * @return True if the requested address has assigned the given role, false otherwise */ function hasRole(address _who, bytes32 _id) public view returns (bool) { return roles[_id][_who] || roles[_id][ANY_ADDR]; } /** * @dev Tell whether a role is frozen * @param _id ID of the role being checked * @return True if the given role is frozen, false otherwise */ function isRoleFrozen(bytes32 _id) public view returns (bool) { return roles[_id][FREEZE_FLAG]; } /** * @dev Internal function to grant a role to a given address * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function _grant(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE); if (!hasRole(_who, _id)) { roles[_id][_who] = true; emit Granted(_id, _who); } } /** * @dev Internal function to revoke a role from a given address * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function _revoke(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); if (hasRole(_who, _id)) { roles[_id][_who] = false; emit Revoked(_id, _who); } } /** * @dev Internal function to freeze a role * @param _id ID of the role to be frozen */ function _freeze(bytes32 _id) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); roles[_id][FREEZE_FLAG] = true; emit Frozen(_id); } /** * @dev Internal function to enact a bulk list of ACL operations */ function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal { require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT); for (uint256 i = 0; i < _op.length; i++) { BulkOp op = _op[i]; if (op == BulkOp.Grant) { _grant(_id[i], _who[i]); } else if (op == BulkOp.Revoke) { _revoke(_id[i], _who[i]); } else if (op == BulkOp.Freeze) { _freeze(_id[i]); } } } } contract ModuleIds { // DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER")) bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6; // GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY")) bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe; // Voting module ID - keccak256(abi.encodePacked("VOTING")) bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346; // PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK")) bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418; // Treasury module ID - keccak256(abi.encodePacked("TREASURY")) bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7; } interface IModulesLinker { /** * @notice Update the implementations of a list of modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external; } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } interface IClock { /** * @dev Ensure that the current term of the clock is up-to-date * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64); /** * @dev Transition up to a certain number of terms to leave the clock up-to-date * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64); /** * @dev Ensure that a certain term has its randomness set * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32); /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64); /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64); /** * @dev Tell the number of terms the clock should transition to be up-to-date * @return Number of terms the clock should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64); /** * @dev Tell the information related to a term based on its ID * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness); /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view returns (bytes32); } contract CourtClock is IClock, TimeHelpers { using SafeMath64 for uint64; string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST"; string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG"; string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET"; string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE"; string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME"; string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS"; string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS"; string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT"; string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME"; // Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1; // Max duration in seconds that a term can last uint64 internal constant MAX_TERM_DURATION = 365 days; // Max time until first term starts since contract is deployed uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION; struct Term { uint64 startTime; // Timestamp when the term started uint64 randomnessBN; // Block number for entropy bytes32 randomness; // Entropy from randomnessBN block hash } // Duration in seconds for each term of the Court uint64 private termDuration; // Last ensured term id uint64 private termId; // List of Court terms indexed by id mapping (uint64 => Term) private terms; event Heartbeat(uint64 previousTermId, uint64 currentTermId); event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime); /** * @dev Ensure a certain term has already been processed * @param _termId Identification number of the term to be checked */ modifier termExists(uint64 _termId) { require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) */ constructor(uint64[2] memory _termParams) public { uint64 _termDuration = _termParams[0]; uint64 _firstTermStartTime = _termParams[1]; require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG); require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME); require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME); termDuration = _termDuration; // No need for SafeMath: we already checked values above terms[0].startTime = _firstTermStartTime - _termDuration; } /** * @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` * terms, the heartbeat function must be called manually instead. * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64) { return _ensureCurrentTerm(); } /** * @notice Transition up to `_maxRequestedTransitions` terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) { return _heartbeat(_maxRequestedTransitions); } /** * @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there * were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given * round will be able to be drafted in the following term. * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32) { // If the randomness for the given term was already computed, return uint64 currentTermId = termId; Term storage term = terms[currentTermId]; bytes32 termRandomness = term.randomness; if (termRandomness != bytes32(0)) { return termRandomness; } // Compute term randomness bytes32 newRandomness = _computeTermRandomness(currentTermId); require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE); term.randomness = newRandomness; return newRandomness; } /** * @dev Tell the term duration of the Court * @return Duration in seconds of the Court term */ function getTermDuration() external view returns (uint64) { return termDuration; } /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64) { return _lastEnsuredTermId(); } /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64) { return _currentTermId(); } /** * @dev Tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64) { return _neededTermTransitions(); } /** * @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the * information returned won't be computed yet. This function allows querying future terms that were not computed yet. * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) { Term storage term = terms[_termId]; return (term.startTime, term.randomnessBN, term.randomness); } /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) { return _computeTermRandomness(_termId); } /** * @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than * `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually. * @return Identification number of the resultant term ID after executing the corresponding transitions */ function _ensureCurrentTerm() internal returns (uint64) { // Check the required number of transitions does not exceeds the max allowed number to be processed automatically uint64 requiredTransitions = _neededTermTransitions(); require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS); // If there are no transitions pending, return the last ensured term id if (uint256(requiredTransitions) == 0) { return termId; } // Process transition if there is at least one pending return _heartbeat(requiredTransitions); } /** * @dev Internal function to transition the Court terms up to a requested number of terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the resultant term ID after executing the requested transitions */ function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) { // Transition the minimum number of terms between the amount requested and the amount actually needed uint64 neededTransitions = _neededTermTransitions(); uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions); require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS); uint64 blockNumber = getBlockNumber64(); uint64 previousTermId = termId; uint64 currentTermId = previousTermId; for (uint256 transition = 1; transition <= transitions; transition++) { // Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64, // even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is // already assumed to fit in uint64. Term storage previousTerm = terms[currentTermId++]; Term storage currentTerm = terms[currentTermId]; _onTermTransitioned(currentTermId); // Set the start time of the new term. Note that we are using a constant term duration value to guarantee // equally long terms, regardless of heartbeats. currentTerm.startTime = previousTerm.startTime.add(termDuration); // In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a // block number that is set once the term has started. Note that this information could not be known beforehand. currentTerm.randomnessBN = blockNumber + 1; } termId = currentTermId; emit Heartbeat(previousTermId, currentTermId); return currentTermId; } /** * @dev Internal function to delay the first term start time only if it wasn't reached yet * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function _delayStartTime(uint64 _newFirstTermStartTime) internal { require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT); Term storage term = terms[0]; uint64 currentFirstTermStartTime = term.startTime.add(termDuration); require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME); // No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration` term.startTime = _newFirstTermStartTime - termDuration; emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime); } /** * @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior. * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal; /** * @dev Internal function to tell the last ensured term identification number * @return Identification number of the last ensured term */ function _lastEnsuredTermId() internal view returns (uint64) { return termId; } /** * @dev Internal function to tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function _currentTermId() internal view returns (uint64) { return termId.add(_neededTermTransitions()); } /** * @dev Internal function to tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function _neededTermTransitions() internal view returns (uint64) { // Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case, // no term transitions are required. uint64 currentTermStartTime = terms[termId].startTime; if (getTimestamp64() < currentTermStartTime) { return uint64(0); } // No need for SafeMath: we already know that the start time of the current term is in the past return (getTimestamp64() - currentTermStartTime) / termDuration; } /** * @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This * function assumes the given term exists. To determine the randomness factor for a term we use the hash of a * block number that is set once the term has started to ensure it cannot be known beforehand. Note that the * hash function being used only works for the 256 most recent block numbers. * @param _termId Identification number of the term being queried * @return Randomness computed for the given term */ function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) { Term storage term = terms[_termId]; require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET); return blockhash(term.randomnessBN); } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); 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, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); 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, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } library PctHelpers { using SafeMath for uint256; uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000) function isValid(uint16 _pct) internal pure returns (bool) { return _pct <= PCT_BASE; } function pct(uint256 self, uint16 _pct) internal pure returns (uint256) { return self.mul(uint256(_pct)) / PCT_BASE; } function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) { return self.mul(_pct) / PCT_BASE; } function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) { // No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16) return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE; } } interface IConfig { /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); } contract CourtConfigData { struct Config { FeesConfig fees; // Full fees-related config DisputesConfig disputes; // Full disputes-related config uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court } struct FeesConfig { IERC20 token; // ERC20 token to be used for the fees of the Court uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000) uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians } struct DisputesConfig { uint64 evidenceTerms; // Max submitting evidence period duration in terms uint64 commitTerms; // Committing period duration in terms uint64 revealTerms; // Revealing period duration in terms uint64 appealTerms; // Appealing period duration in terms uint64 appealConfirmTerms; // Confirmation appeal period duration in terms uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked uint256 maxRegularAppealRounds; // Before the final appeal uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000) uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000) } struct DraftConfig { IERC20 feeToken; // ERC20 token to be used for the fees of the Court uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians } } contract CourtConfig is IConfig, CourtConfigData { using SafeMath64 for uint64; using PctHelpers for uint256; string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM"; string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT"; string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT"; string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS"; string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION"; string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER"; string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR"; string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR"; string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE"; // Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year) uint64 internal constant MAX_ADJ_STATE_DURATION = 8670; // Cap the max number of regular appeal rounds uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10; // Future term ID in which a config change has been scheduled uint64 private configChangeTermId; // List of all the configs used in the Court Config[] private configs; // List of configs indexed by id mapping (uint64 => uint256) private configIdByTerm; event NewConfig(uint64 fromTermId, uint64 courtConfigId); /** * @dev Constructor function * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public { // Leave config at index 0 empty for non-scheduled config changes configs.length = 1; _setConfig( 0, 0, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); /** * @dev Tell the term identification number of the next scheduled config change * @return Term identification number of the next scheduled config change */ function getConfigChangeTermId() external view returns (uint64) { return configChangeTermId; } /** * @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none * @param _termId Identification number of the new current term that has been transitioned */ function _ensureTermConfig(uint64 _termId) internal { // If the term being transitioned had no config change scheduled, keep the previous one uint256 currentConfigId = configIdByTerm[_termId]; if (currentConfigId == 0) { uint256 previousConfigId = configIdByTerm[_termId.sub(1)]; configIdByTerm[_termId] = previousConfigId; } } /** * @dev Assumes that sender it's allowed (either it's from governor or it's on init) * @param _termId Identification number of the current Court term * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees. * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function _setConfig( uint64 _termId, uint64 _fromTermId, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) internal { // If the current term is not zero, changes must be scheduled at least after the current period. // No need to ensure delays for on-going disputes since these already use their creation term for that. require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM); // Make sure appeal collateral factors are greater than zero require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR); // Make sure the given penalty and final round reduction pcts are not greater than 100% require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT); require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT); // Disputes must request at least one guardian to be drafted initially require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER); // Prevent that further rounds have zero guardians require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR); // Make sure the max number of appeals allowed does not reach the limit uint256 _maxRegularAppealRounds = _roundParams[2]; bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT; require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS); // Make sure each adjudication round phase duration is valid for (uint i = 0; i < _roundStateDurations.length; i++) { require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION); } // Make sure min active balance is not zero require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE); // If there was a config change already scheduled, reset it (in that case we will overwrite last array item). // Otherwise, schedule a new config. if (configChangeTermId > _termId) { configIdByTerm[configChangeTermId] = 0; } else { configs.length++; } uint64 courtConfigId = uint64(configs.length - 1); Config storage config = configs[courtConfigId]; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _maxRegularAppealRounds, finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; configIdByTerm[_fromTermId] = courtConfigId; configChangeTermId = _fromTermId; emit NewConfig(_fromTermId, courtConfigId); } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of guardian tokens that can be activated */ function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); FeesConfig storage feesConfig = config.fees; feeToken = feesConfig.token; fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee]; DisputesConfig storage disputesConfig = config.disputes; roundStateDurations = [ disputesConfig.evidenceTerms, disputesConfig.commitTerms, disputesConfig.revealTerms, disputesConfig.appealTerms, disputesConfig.appealConfirmTerms ]; pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction]; roundParams = [ disputesConfig.firstRoundGuardiansNumber, disputesConfig.appealStepFactor, uint64(disputesConfig.maxRegularAppealRounds), disputesConfig.finalRoundLockTerms ]; appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor]; minActiveBalance = config.minActiveBalance; } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Minimum amount of guardian tokens that can be activated at the given term */ function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return config.minActiveBalance; } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Court config for the given term */ function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) { uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId); return configs[id]; } /** * @dev Internal function to get the Court config ID for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Identification number of the config for the given terms */ function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { // If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config if (_termId <= _lastEnsuredTermId) { return configIdByTerm[_termId]; } // If the given term is in the future but there is a config change scheduled before it, use the incoming config uint64 scheduledChangeTermId = configChangeTermId; if (scheduledChangeTermId <= _termId) { return configIdByTerm[scheduledChangeTermId]; } // If no changes are scheduled, use the Court config of the last ensured term return configIdByTerm[_lastEnsuredTermId]; } } interface IDisputeManager { enum DisputeState { PreDraft, Adjudicating, Ruled } enum AdjudicationState { Invalid, Committing, Revealing, Appealing, ConfirmingAppeal, Ended } /** * @dev Create a dispute to be drafted in a future term * @param _subject Arbitrable instance creating the dispute * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _subject Arbitrable instance submitting the dispute * @param _disputeId Identification number of the dispute receiving new evidence * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence of the dispute */ function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _subject IArbitrable instance requesting to close the evidence submission period * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external; /** * @dev Draft guardians for the next round of a dispute * @param _disputeId Identification number of the dispute to be drafted */ function draft(uint256 _disputeId) external; /** * @dev Appeal round of a dispute in favor of a certain ruling * @param _disputeId Identification number of the dispute being appealed * @param _roundId Identification number of the dispute round being appealed * @param _ruling Ruling appealing a dispute round in favor of */ function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Confirm appeal for a round of a dispute in favor of a ruling * @param _disputeId Identification number of the dispute confirming an appeal of * @param _roundId Identification number of the dispute round confirming an appeal of * @param _ruling Ruling being confirmed against a dispute round appeal */ function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Compute the final ruling for a dispute * @param _disputeId Identification number of the dispute to compute its final ruling * @return subject Arbitrable instance associated to the dispute * @return finalRuling Final ruling decided for the given dispute */ function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling); /** * @dev Settle penalties for a round of a dispute * @param _disputeId Identification number of the dispute to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _guardiansToSettle Maximum number of guardians to be slashed in this call */ function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external; /** * @dev Claim rewards for a round of a dispute for guardian * @dev For regular rounds, it will only reward winning guardians * @param _disputeId Identification number of the dispute to settle rewards for * @param _roundId Identification number of the dispute round to settle rewards for * @param _guardian Address of the guardian to settle their rewards */ function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external; /** * @dev Settle appeal deposits for a round of a dispute * @param _disputeId Identification number of the dispute to settle appeal deposits for * @param _roundId Identification number of the dispute round to settle appeal deposits for */ function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external; /** * @dev Tell the amount of token fees required to create a dispute * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees to be paid for a dispute at the given term */ function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount); /** * @dev Tell information of a certain dispute * @param _disputeId Identification number of the dispute being queried * @return subject Arbitrable subject being disputed * @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled * @return finalRuling The winning ruling in case the dispute is finished * @return lastRoundId Identification number of the last round created for the dispute * @return createTermId Identification number of the term when the dispute was created */ function getDispute(uint256 _disputeId) external view returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId); /** * @dev Tell information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return draftTerm Term from which the requested round can be drafted * @return delayedTerms Number of terms the given round was delayed based on its requested draft term id * @return guardiansNumber Number of guardians requested for the round * @return selectedGuardians Number of guardians already selected for the requested round * @return settledPenalties Whether or not penalties have been settled for the requested round * @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round * @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round * @return state Adjudication state of the requested round */ function getRound(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 draftTerm, uint64 delayedTerms, uint64 guardiansNumber, uint64 selectedGuardians, uint256 guardianFees, bool settledPenalties, uint256 collectedTokens, uint64 coherentGuardians, AdjudicationState state ); /** * @dev Tell appeal-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return maker Address of the account appealing the given round * @return appealedRuling Ruling confirmed by the appealer of the given round * @return taker Address of the account confirming the appeal of the given round * @return opposedRuling Ruling confirmed by the appeal taker of the given round */ function getAppeal(uint256 _disputeId, uint256 _roundId) external view returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling); /** * @dev Tell information related to the next round due to an appeal of a certain round given. * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round requesting the appeal details of * @return nextRoundStartTerm Term ID from which the next round will start * @return nextRoundGuardiansNumber Guardians number for the next round * @return newDisputeState New state for the dispute associated to the given round after the appeal * @return feeToken ERC20 token used for the next round fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round * @return totalFees Total amount of fees for a regular round at the given term * @return appealDeposit Amount to be deposit of fees for a regular round at the given term * @return confirmAppealDeposit Total amount of fees for a regular round at the given term */ function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 nextRoundStartTerm, uint64 nextRoundGuardiansNumber, DisputeState newDisputeState, IERC20 feeToken, uint256 totalFees, uint256 guardianFees, uint256 appealDeposit, uint256 confirmAppealDeposit ); /** * @dev Tell guardian-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @param _guardian Address of the guardian being queried * @return weight Guardian weight drafted for the requested round * @return rewarded Whether or not the given guardian was rewarded based on the requested round */ function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded); } contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL { string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR"; string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS"; string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET"; string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED"; string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED"; string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE"; string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET"; string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT"; string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH"; address private constant ZERO_ADDRESS = address(0); /** * @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules */ struct Governor { address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system } /** * @dev Module information */ struct Module { bytes32 id; // ID associated to a module bool disabled; // Whether the module is disabled } // Governor addresses of the system Governor private governor; // List of current modules registered for the system indexed by ID mapping (bytes32 => address) internal currentModules; // List of all historical modules registered for the system indexed by address mapping (address => Module) internal allModules; // List of custom function targets indexed by signature mapping (bytes4 => address) internal customFunctions; event ModuleSet(bytes32 id, address addr); event ModuleEnabled(bytes32 id, address addr); event ModuleDisabled(bytes32 id, address addr); event CustomFunctionSet(bytes4 signature, address target); event FundsGovernorChanged(address previousGovernor, address currentGovernor); event ConfigGovernorChanged(address previousGovernor, address currentGovernor); event ModulesGovernorChanged(address previousGovernor, address currentGovernor); /** * @dev Ensure the msg.sender is the funds governor */ modifier onlyFundsGovernor { require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyConfigGovernor { require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyModulesGovernor { require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the given dispute manager is active */ modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) { require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) * @param _governors Array containing: * 0. _fundsGovernor Address of the funds governor * 1. _configGovernor Address of the config governor * 2. _modulesGovernor Address of the modules governor * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public CourtClock(_termParams) CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance) { _setFundsGovernor(_governors[0]); _setConfigGovernor(_governors[1]); _setModulesGovernor(_governors[2]); } /** * @dev Fallback function allows to forward calls to a specific address in case it was previously registered * Note the sender will be always the controller in case it is forwarded */ function () external payable { address target = customFunctions[msg.sig]; require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET); // solium-disable-next-line security/no-call-value (bool success,) = address(target).call.value(msg.value)(msg.data); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) let result := success switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @notice Change Court configuration params * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function setConfig( uint64 _fromTermId, IERC20 _feeToken, uint256[3] calldata _fees, uint64[5] calldata _roundStateDurations, uint16[2] calldata _pcts, uint64[4] calldata _roundParams, uint256[2] calldata _appealCollateralParams, uint256 _minActiveBalance ) external onlyConfigGovernor { uint64 currentTermId = _ensureCurrentTerm(); _setConfig( currentTermId, _fromTermId, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @notice Delay the Court start time to `_newFirstTermStartTime` * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor { _delayStartTime(_newFirstTermStartTime); } /** * @notice Change funds governor address to `_newFundsGovernor` * @param _newFundsGovernor Address of the new funds governor to be set */ function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor { require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setFundsGovernor(_newFundsGovernor); } /** * @notice Change config governor address to `_newConfigGovernor` * @param _newConfigGovernor Address of the new config governor to be set */ function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor { require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setConfigGovernor(_newConfigGovernor); } /** * @notice Change modules governor address to `_newModulesGovernor` * @param _newModulesGovernor Address of the new governor to be set */ function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor { require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setModulesGovernor(_newModulesGovernor); } /** * @notice Remove the funds governor. Set the funds governor to the zero address. * @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore */ function ejectFundsGovernor() external onlyFundsGovernor { _setFundsGovernor(ZERO_ADDRESS); } /** * @notice Remove the modules governor. Set the modules governor to the zero address. * @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore */ function ejectModulesGovernor() external onlyModulesGovernor { _setModulesGovernor(ZERO_ADDRESS); } /** * @notice Grant `_id` role to `_who` * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function grant(bytes32 _id, address _who) external onlyConfigGovernor { _grant(_id, _who); } /** * @notice Revoke `_id` role from `_who` * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); } /** * @notice Freeze `_id` role * @param _id ID of the role to be frozen */ function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); } /** * @notice Enact a bulk list of ACL operations */ function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor { _bulk(_op, _id, _who); } /** * @notice Set module `_id` to `_addr` * @param _id ID of the module to be set * @param _addr Address of the module to be set */ function setModule(bytes32 _id, address _addr) external onlyModulesGovernor { _setModule(_id, _addr); } /** * @notice Set and link many modules at once * @param _newModuleIds List of IDs of the new modules to be set * @param _newModuleAddresses List of addresses of the new modules to be set * @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set * @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set */ function setModules( bytes32[] calldata _newModuleIds, address[] calldata _newModuleAddresses, bytes32[] calldata _newModuleLinks, address[] calldata _currentModulesToBeSynced ) external onlyModulesGovernor { // We only care about the modules being set, links are optional require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH); // First set the addresses of the new modules or the modules to be updated for (uint256 i = 0; i < _newModuleIds.length; i++) { _setModule(_newModuleIds[i], _newModuleAddresses[i]); } // Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies) _syncModuleLinks(_newModuleAddresses, _newModuleLinks); // Finally sync the links of the existing modules to be synced to the new modules being set _syncModuleLinks(_currentModulesToBeSynced, _newModuleIds); } /** * @notice Sync modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules included in the sync */ function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor { require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH); _syncModuleLinks(_modulesToBeSynced, _idsToBeSet); } /** * @notice Disable module `_addr` * @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule` * @param _addr Address of the module to be disabled */ function disableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED); module.disabled = true; emit ModuleDisabled(module.id, _addr); } /** * @notice Enable module `_addr` * @param _addr Address of the module to be enabled */ function enableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(module.disabled, ERROR_MODULE_ALREADY_ENABLED); module.disabled = false; emit ModuleEnabled(module.id, _addr); } /** * @notice Set custom function `_sig` for `_target` * @param _sig Signature of the function to be set * @param _target Address of the target implementation to be registered for the given signature */ function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getConfigAt(_termId, lastEnsuredTermId); } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getDraftConfig(_termId, lastEnsuredTermId); } /** * @dev Tell the min active balance config at a certain term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getMinActiveBalance(_termId, lastEnsuredTermId); } /** * @dev Tell the address of the funds governor * @return Address of the funds governor */ function getFundsGovernor() external view returns (address) { return governor.funds; } /** * @dev Tell the address of the config governor * @return Address of the config governor */ function getConfigGovernor() external view returns (address) { return governor.config; } /** * @dev Tell the address of the modules governor * @return Address of the modules governor */ function getModulesGovernor() external view returns (address) { return governor.modules; } /** * @dev Tell if a given module is active * @param _id ID of the module to be checked * @param _addr Address of the module to be checked * @return True if the given module address has the requested ID and is enabled */ function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; } /** * @dev Tell the current ID and disable status of a module based on a given address * @param _addr Address of the requested module * @return id ID of the module being queried * @return disabled Whether the module has been disabled */ function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) { Module storage module = allModules[_addr]; id = module.id; disabled = module.disabled; } /** * @dev Tell the current address and disable status of a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function getModule(bytes32 _id) external view returns (address addr, bool disabled) { return _getModule(_id); } /** * @dev Tell the information for the current DisputeManager module * @return addr Current address of the DisputeManager module * @return disabled Whether the module has been disabled */ function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); } /** * @dev Tell the information for the current GuardiansRegistry module * @return addr Current address of the GuardiansRegistry module * @return disabled Whether the module has been disabled */ function getGuardiansRegistry() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_GUARDIANS_REGISTRY); } /** * @dev Tell the information for the current Voting module * @return addr Current address of the Voting module * @return disabled Whether the module has been disabled */ function getVoting() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_VOTING); } /** * @dev Tell the information for the current PaymentsBook module * @return addr Current address of the PaymentsBook module * @return disabled Whether the module has been disabled */ function getPaymentsBook() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_PAYMENTS_BOOK); } /** * @dev Tell the information for the current Treasury module * @return addr Current address of the Treasury module * @return disabled Whether the module has been disabled */ function getTreasury() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_TREASURY); } /** * @dev Tell the target registered for a custom function * @param _sig Signature of the function being queried * @return Address of the target where the function call will be forwarded */ function getCustomFunction(bytes4 _sig) external view returns (address) { return customFunctions[_sig]; } /** * @dev Internal function to set the address of the funds governor * @param _newFundsGovernor Address of the new config governor to be set */ function _setFundsGovernor(address _newFundsGovernor) internal { emit FundsGovernorChanged(governor.funds, _newFundsGovernor); governor.funds = _newFundsGovernor; } /** * @dev Internal function to set the address of the config governor * @param _newConfigGovernor Address of the new config governor to be set */ function _setConfigGovernor(address _newConfigGovernor) internal { emit ConfigGovernorChanged(governor.config, _newConfigGovernor); governor.config = _newConfigGovernor; } /** * @dev Internal function to set the address of the modules governor * @param _newModulesGovernor Address of the new modules governor to be set */ function _setModulesGovernor(address _newModulesGovernor) internal { emit ModulesGovernorChanged(governor.modules, _newModulesGovernor); governor.modules = _newModulesGovernor; } /** * @dev Internal function to set an address as the current implementation for a module * Note that the disabled condition is not affected, if the module was not set before it will be enabled by default * @param _id Id of the module to be set * @param _addr Address of the module to be set */ function _setModule(bytes32 _id, address _addr) internal { require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT); currentModules[_id] = _addr; allModules[_addr].id = _id; emit ModuleSet(_id, _addr); } /** * @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules to be linked */ function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal { address[] memory addressesToBeSet = new address[](_idsToBeSet.length); // Load the addresses associated with the requested module ids for (uint256 i = 0; i < _idsToBeSet.length; i++) { address moduleAddress = _getModuleAddress(_idsToBeSet[i]); Module storage module = allModules[moduleAddress]; _ensureModuleExists(module); addressesToBeSet[i] = moduleAddress; } // Update the links of all the requested modules for (uint256 j = 0; j < _modulesToBeSynced.length; j++) { IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet); } } /** * @dev Internal function to notify when a term has been transitioned * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal { _ensureTermConfig(_termId); } /** * @dev Internal function to check if a module was set * @param _module Module to be checked */ function _ensureModuleExists(Module storage _module) internal view { require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET); } /** * @dev Internal function to tell the information for a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); } /** * @dev Tell the current address for a module by ID * @param _id ID of the module being queried * @return Current address of the requested module */ function _getModuleAddress(bytes32 _id) internal view returns (address) { return currentModules[_id]; } /** * @dev Tell whether a module is disabled * @param _addr Address of the module being queried * @return True if the module is disabled, false otherwise */ function _isModuleDisabled(address _addr) internal view returns (bool) { return allModules[_addr].disabled; } } contract AragonCourt is IArbitrator, Controller { using Uint256Helpers for uint256; /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) * @param _governors Array containing: * 0. _fundsGovernor Address of the funds governor * 1. _configGovernor Address of the config governor * 2. _modulesGovernor Address of the modules governor * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public Controller( _termParams, _governors, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ) { // solium-disable-previous-line no-empty-blocks } /** * @notice Create a dispute with `_possibleRulings` possible rulings * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256) { IArbitrable subject = IArbitrable(msg.sender); return _disputeManager().createDispute(subject, _possibleRulings.toUint8(), _metadata); } /** * @notice Submit `_evidence` as evidence from `_submitter` for dispute #`_disputeId` * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external { _submitEvidence(_disputeManager(), _disputeId, _submitter, _evidence); } /** * @notice Submit `_evidence` as evidence from `_submitter` for dispute #`_disputeId` * @dev This entry point can be used to submit evidences to previous Dispute Manager instances * @param _disputeManager Dispute manager to be used * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidenceForModule(IDisputeManager _disputeManager, uint256 _disputeId, address _submitter, bytes calldata _evidence) external onlyActiveDisputeManager(_disputeManager) { _submitEvidence(_disputeManager, _disputeId, _submitter, _evidence); } /** * @notice Close the evidence period of dispute #`_disputeId` * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external { _closeEvidencePeriod(_disputeManager(), _disputeId); } /** * @notice Close the evidence period of dispute #`_disputeId` * @dev This entry point can be used to close evidence periods on previous Dispute Manager instances * @param _disputeManager Dispute manager to be used * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriodForModule(IDisputeManager _disputeManager, uint256 _disputeId) external onlyActiveDisputeManager(_disputeManager) { _closeEvidencePeriod(_disputeManager, _disputeId); } /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Arbitrable instance associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external returns (address subject, uint256 ruling) { return _rule(_disputeManager(), _disputeId); } /** * @notice Rule dispute #`_disputeId` if ready * @dev This entry point can be used to rule disputes on previous Dispute Manager instances * @param _disputeManager Dispute manager to be used * @param _disputeId Identification number of the dispute to be ruled * @return subject Arbitrable instance associated to the dispute * @return ruling Ruling number computed for the given dispute */ function ruleForModule(IDisputeManager _disputeManager, uint256 _disputeId) external onlyActiveDisputeManager(_disputeManager) returns (address subject, uint256 ruling) { return _rule(_disputeManager, _disputeId); } /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount) { IDisputeManager disputeManager = _disputeManager(); recipient = address(disputeManager); (feeToken, feeAmount) = disputeManager.getDisputeFees(); } /** * @dev Tell the payments recipient address * @return Address of the payments recipient module */ function getPaymentsRecipient() external view returns (address) { return currentModules[MODULE_ID_PAYMENTS_BOOK]; } /** * @dev Internal function to submit evidence for a dispute * @param _disputeManager Dispute manager to be used * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function _submitEvidence(IDisputeManager _disputeManager, uint256 _disputeId, address _submitter, bytes memory _evidence) internal { IArbitrable subject = IArbitrable(msg.sender); _disputeManager.submitEvidence(subject, _disputeId, _submitter, _evidence); } /** * @dev Internal function to close the evidence period of a dispute * @param _disputeManager Dispute manager to be used * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function _closeEvidencePeriod(IDisputeManager _disputeManager, uint256 _disputeId) internal { IArbitrable subject = IArbitrable(msg.sender); _disputeManager.closeEvidencePeriod(subject, _disputeId); } /** * @dev Internal function to rule a dispute * @param _disputeManager Dispute manager to be used * @param _disputeId Identification number of the dispute to be ruled * @return subject Arbitrable instance associated to the dispute * @return ruling Ruling number computed for the given dispute */ function _rule(IDisputeManager _disputeManager, uint256 _disputeId) internal returns (address subject, uint256 ruling) { (IArbitrable _subject, uint8 _ruling) = _disputeManager.computeRuling(_disputeId); return (address(_subject), uint256(_ruling)); } /** * @dev Internal function to tell the current DisputeManager module * @return Current DisputeManager module */ function _disputeManager() internal view returns (IDisputeManager) { return IDisputeManager(_getModuleAddress(MODULE_ID_DISPUTE_MANAGER)); } }
* @notice Rule dispute #`_disputeId` if ready @param _disputeId Identification number of the dispute to be ruled @return subject Arbitrable instance associated to the dispute @return ruling Ruling number computed for the given dispute/
function rule(uint256 _disputeId) external returns (address subject, uint256 ruling) { return _rule(_disputeManager(), _disputeId); }
1,566,096
[ 1, 2175, 1015, 2507, 1375, 67, 2251, 2507, 548, 68, 309, 5695, 225, 389, 2251, 2507, 548, 13128, 1480, 1300, 434, 326, 1015, 2507, 358, 506, 1720, 72, 327, 3221, 1201, 3682, 354, 7119, 791, 3627, 358, 326, 1015, 2507, 327, 436, 332, 310, 534, 332, 310, 1300, 8470, 364, 326, 864, 1015, 2507, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1720, 12, 11890, 5034, 389, 2251, 2507, 548, 13, 3903, 1135, 261, 2867, 3221, 16, 2254, 5034, 436, 332, 310, 13, 288, 203, 3639, 327, 389, 5345, 24899, 2251, 2507, 1318, 9334, 389, 2251, 2507, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xD1891d7fe048B9A0e047b2f017385c52E4B7a316/sources/contracts/Contract.sol
5% of jackpot goes to contract
uint256 contractFee = (jackpot * CONTRACT_FEE_PERCENTAGE) / 100;
4,711,324
[ 1, 25, 9, 434, 525, 484, 13130, 13998, 358, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 6835, 14667, 273, 261, 78, 484, 13130, 380, 8020, 2849, 1268, 67, 8090, 41, 67, 3194, 19666, 2833, 13, 342, 2130, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // Enables not using SafeMath pragma solidity =0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract LiquidityStaker is ReentrancyGuard { using SafeERC20 for IERC20; IERC20 private _WIND; IERC20 private _LP; // WIND per block // Set to 0.1, which will mean 64800 per month // With an initial balance of 1 million, this will last roughly a year (see notes below on divisorOfPoolAtStart) // That said, it is technically long term viable due to potential arbitrary addition of Whirlwinds // That would allow using privacy mining funds as staking rewards // This is something to discuss down the road uint256 public constant WIND_PER_BLOCK = 1e17; struct Staker { // Block deposited on/most recent block they claimed rewards uint256 lastBlock; // Amount deposited uint256 amount; // Rewards are based on historical percent of LP pool and current percent // Encourages getting in early, yet also doesn't allow the first party to always claim 100% // Also moves distribution closer to target by not having potentially infinite amounts (always depositing more and more) // Still causes target exceedance; maximum of 250%, yet practical of ~150% uint256 divisorOfPoolAtStart; } mapping(address => Staker) private _stakers; event Deposit(address indexed staker, uint256 amount, uint256 divisorOfPool); event Rewards(address indexed staker, uint256 amount, uint256 divisorUsed); event Withdraw(address indexed staker, uint256 amount); constructor(address WIND, address LP) { _WIND = IERC20(WIND); _LP = IERC20(LP); } function getStakedAmount(address staker) external view returns (uint256) { return _stakers[staker].amount; } // Returns the divisor to use to get the staker's percentage weighted version of an amount function getCurrentDivisorForPool(address staker) public view returns (uint256) { // Will revert for non-stakers return _LP.balanceOf(address(this)) / _stakers[staker].amount; } function getPercentageDivisor(address staker) public returns (uint256) { uint256 currentDivisor = getCurrentDivisorForPool(staker); // The percent of pool at start is meant to reward early stakers // If late in life, stakes are withdrawn, then the currentDivisor would penalize older stakers // To solve this, update it to the lowest divisor found (the highest staked percentage version) if (currentDivisor < _stakers[staker].divisorOfPoolAtStart) { _stakers[staker].divisorOfPoolAtStart = currentDivisor; } return (_stakers[staker].divisorOfPoolAtStart + currentDivisor) / 2; } function getRewards(address staker) public returns (uint256, uint256) { // Prevent a revert when the divisor code is called if (_stakers[staker].amount == 0) { return (0, 0); } uint256 divisor = getPercentageDivisor(staker); return ( (WIND_PER_BLOCK * (block.number - _stakers[staker].lastBlock)) / divisor, divisor ); } function _claimRewards(address staker) internal { // A check if the last interaction block is the current block isn't needed // The block differential is a direct factor in the rewards calculation (uint256 rewards, uint256 divisor) = getRewards(staker); // Always update the last block due to usage below _stakers[staker].lastBlock = block.number; // Only call transfer when there's an amount if (rewards != 0) { _WIND.safeTransfer(staker, rewards); emit Rewards(staker, rewards, divisor); } } // nonReentrant for extra safety; none of these should NEED it function claimRewards(address staker) external nonReentrant { _claimRewards(staker); } function deposit(uint256 amount) external nonReentrant { // End meaningless transactions now require(amount != 0, "LiquidityStaker: Cannot deposit 0 WIND"); // If this is a new staker, create them if (_stakers[msg.sender].amount == 0) { _stakers[msg.sender] = Staker( block.number, amount, 0 ); // Transfer the liquidity tokens // Done here so we can set the divisor via the actual function // Safe due to above Staker set (which can cause a div by 0 revert) and nonReentrant _LP.safeTransferFrom(msg.sender, address(this), amount); _stakers[msg.sender].divisorOfPoolAtStart = getCurrentDivisorForPool(msg.sender); emit Deposit(msg.sender, amount, _stakers[msg.sender].divisorOfPoolAtStart); // Return now so we don't further edit this staker return; } // Else... // Claim existing rewards so this deposit doesn't clear them // Also updates last block _claimRewards(msg.sender); // Update the amount now before calling an external contract // Follow checks, effects, interactions when possible, despite not doing it above _stakers[msg.sender].amount += amount; // Transfer the liquidity tokens _LP.safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, amount, _stakers[msg.sender].divisorOfPoolAtStart); } function withdraw(uint256 amount) external nonReentrant { // Update last block/prevent rewards from being cleared _claimRewards(msg.sender); _stakers[msg.sender].amount -= amount; // Transfer the LPs _LP.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, amount); } // Withdraw without claiming rewards // Used to stop funds from being trapped if LP rewards run out function emergencyWithdraw() external nonReentrant { uint256 amount = _stakers[msg.sender].amount; // Zero the staker's amount // This will cause them to be recognized as a new staker on the next deposit // Also prevents further emegency withdraws, of course _stakers[msg.sender].amount = 0; // Transfer the LPs _LP.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, amount); } }
End meaningless transactions now If this is a new staker, create them Transfer the liquidity tokens Done here so we can set the divisor via the actual function Safe due to above Staker set (which can cause a div by 0 revert) and nonReentrant Return now so we don't further edit this staker
function deposit(uint256 amount) external nonReentrant { require(amount != 0, "LiquidityStaker: Cannot deposit 0 WIND"); if (_stakers[msg.sender].amount == 0) { _stakers[msg.sender] = Staker( block.number, amount, 0 ); _LP.safeTransferFrom(msg.sender, address(this), amount); _stakers[msg.sender].divisorOfPoolAtStart = getCurrentDivisorForPool(msg.sender); emit Deposit(msg.sender, amount, _stakers[msg.sender].divisorOfPoolAtStart); return; } emit Deposit(msg.sender, amount, _stakers[msg.sender].divisorOfPoolAtStart); }
1,022,879
[ 1, 1638, 12256, 2656, 8938, 2037, 971, 333, 353, 279, 394, 384, 6388, 16, 752, 2182, 12279, 326, 4501, 372, 24237, 2430, 8677, 2674, 1427, 732, 848, 444, 326, 15013, 3970, 326, 3214, 445, 14060, 6541, 358, 5721, 934, 6388, 444, 261, 12784, 848, 4620, 279, 3739, 635, 374, 15226, 13, 471, 1661, 426, 8230, 970, 2000, 2037, 1427, 732, 2727, 1404, 9271, 3874, 333, 384, 6388, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 443, 1724, 12, 11890, 5034, 3844, 13, 3903, 1661, 426, 8230, 970, 288, 203, 565, 2583, 12, 8949, 480, 374, 16, 315, 48, 18988, 24237, 510, 6388, 30, 14143, 443, 1724, 374, 24482, 8863, 203, 203, 565, 309, 261, 67, 334, 581, 414, 63, 3576, 18, 15330, 8009, 8949, 422, 374, 13, 288, 203, 1377, 389, 334, 581, 414, 63, 3576, 18, 15330, 65, 273, 934, 6388, 12, 203, 3639, 1203, 18, 2696, 16, 203, 3639, 3844, 16, 203, 3639, 374, 203, 1377, 11272, 203, 203, 1377, 389, 14461, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 203, 1377, 389, 334, 581, 414, 63, 3576, 18, 15330, 8009, 2892, 12385, 951, 2864, 861, 1685, 273, 5175, 7244, 12385, 1290, 2864, 12, 3576, 18, 15330, 1769, 203, 203, 1377, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 3844, 16, 389, 334, 581, 414, 63, 3576, 18, 15330, 8009, 2892, 12385, 951, 2864, 861, 1685, 1769, 203, 203, 1377, 327, 31, 203, 565, 289, 203, 203, 203, 203, 203, 565, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 3844, 16, 389, 334, 581, 414, 63, 3576, 18, 15330, 8009, 2892, 12385, 951, 2864, 861, 1685, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { BoringMath, BoringMath128 } from "./libraries/boring/BoringMath.sol"; import { BoringOwnable } from "./libraries/boring/BoringOwnable.sol"; import { BoringERC20 } from "./libraries/boring/BoringERC20.sol"; import { IRewarder } from "./interfaces/sushi/IRewarder.sol"; import { IMasterChefV2 } from "./interfaces/sushi/IMasterChefV2.sol"; import "hardhat/console.sol"; contract ALCXRewarder is IRewarder, BoringOwnable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; IERC20 private immutable rewardToken; IMasterChefV2 private immutable MC_V2; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of SUSHI entitled to the user. struct UserInfo { uint256 amount; uint256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of SUSHI to distribute per block. struct PoolInfo { uint128 accTokenPerShare; uint64 lastRewardBlock; uint64 allocPoint; } uint256[] public poolIds; /// @notice Info of each pool. mapping(uint256 => PoolInfo) public poolInfo; /// @notice Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 totalAllocPoint; uint256 public tokenPerBlock; uint256 private constant ACC_TOKEN_PRECISION = 1e12; event PoolAdded(uint256 indexed pid, uint256 allocPoint); event PoolSet(uint256 indexed pid, uint256 allocPoint); event PoolUpdated(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accTokenPerShare); event OnReward(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event RewardRateUpdated(uint256 oldRate, uint256 newRate); modifier onlyMCV2 { require(msg.sender == address(MC_V2), "ALCXRewarder::onlyMCV2: only MasterChef V2 can call this function."); _; } constructor( IERC20 _rewardToken, uint256 _tokenPerBlock, IMasterChefV2 _MCV2 ) public { require(Address.isContract(address(_rewardToken)), "ALCXRewarder: reward token must be a valid contract"); require(Address.isContract(address(_MCV2)), "ALCXRewarder: MasterChef V2 must be a valid contract"); rewardToken = _rewardToken; tokenPerBlock = _tokenPerBlock; MC_V2 = _MCV2; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _pid Pid on MCV2 function addPool(uint256 _pid, uint256 allocPoint) public onlyOwner { require(poolInfo[_pid].lastRewardBlock == 0, "ALCXRewarder::add: cannot add existing pool"); uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); poolInfo[_pid] = PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accTokenPerShare: 0 }); poolIds.push(_pid); emit PoolAdded(_pid, allocPoint); } /// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. function setPool(uint256 _pid, uint256 _allocPoint) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); emit PoolSet(_pid, _allocPoint); } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = MC_V2.lpToken(pid).balanceOf(address(MC_V2)); if (lpSupply > 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 tokenReward = blocks.mul(tokenPerBlock).mul(pool.allocPoint) / totalAllocPoint; pool.accTokenPerShare = pool.accTokenPerShare.add( (tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply).to128() ); } pool.lastRewardBlock = block.number.to64(); poolInfo[pid] = pool; emit PoolUpdated(pid, pool.lastRewardBlock, lpSupply, pool.accTokenPerShare); } } /// @notice Update reward variables for all pools /// @dev Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) public { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @dev Sets the distribution reward rate. This will also update all of the pools. /// @param _tokenPerBlock The number of tokens to distribute per block function setRewardRate(uint256 _tokenPerBlock, uint256[] calldata _pids) external onlyOwner { massUpdatePools(_pids); uint256 oldRate = tokenPerBlock; tokenPerBlock = _tokenPerBlock; emit RewardRateUpdated(oldRate, _tokenPerBlock); } function onSushiReward( uint256 pid, address _user, address to, uint256, uint256 lpToken ) external override onlyMCV2 { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][_user]; uint256 pending; // if user had deposited if (user.amount > 0) { pending = (user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt); rewardToken.safeTransfer(to, pending); } user.amount = lpToken; user.rewardDebt = user.rewardDebt.add(pending); emit OnReward(_user, pid, pending, to); } function pendingTokens( uint256 pid, address user, uint256 ) external view override returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts) { IERC20[] memory _rewardTokens = new IERC20[](1); _rewardTokens[0] = (rewardToken); uint256[] memory _rewardAmounts = new uint256[](1); _rewardAmounts[0] = pendingToken(pid, user); return (_rewardTokens, _rewardAmounts); } /// @notice View function to see pending Token /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending SUSHI reward for a given user. function pendingToken(uint256 _pid, address _user) public view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTokenPerShare = pool.accTokenPerShare; uint256 lpSupply = MC_V2.lpToken(_pid).balanceOf(address(MC_V2)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 tokenReward = blocks.mul(tokenPerBlock).mul(pool.allocPoint) / totalAllocPoint; accTokenPerShare = accTokenPerShare.add(tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply); } pending = (user.amount.mul(accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath::add: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath::sub: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath::mul: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath::to128: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath::to64: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath::to32: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath128::add: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath128::sub: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath64::add: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath64::sub: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath32::add: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath32::sub: Underflow"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Audit on 5-Jan-2021 by Keno and BoringCrypto // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "BoringOwnable::transferOwnership: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "BoringOwnable::claimOwnership: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "BoringOwnable::onlyOwner: caller is not the owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while (i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20::safeTransfer: transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require( success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20::safeTransferFrom: transfer failed" ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../libraries/boring/BoringERC20.sol"; interface IRewarder { using BoringERC20 for IERC20; function onSushiReward( uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount ) external; function pendingTokens( uint256 pid, address user, uint256 sushiAmount ) external view returns (IERC20[] memory, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../libraries/boring/BoringERC20.sol"; interface IMasterChefV2 { using BoringERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } function lpToken(uint256 pid) external view returns (IERC20); function poolInfo(uint256 pid) external view returns (PoolInfo memory); function totalAllocPoint() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "hardhat/console.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { StakingPools } from "./StakingPools.sol"; import { FixedPointMath } from "./libraries/math/FixedPointMath.sol"; import { IMintableERC20 } from "./interfaces/token/ERC20/IMintableERC20.sol"; import { Pool } from "./libraries/pools/Pool.sol"; import { Stake } from "./libraries/pools/Stake.sol"; import "hardhat/console.sol"; /// @title StakingPools // ___ __ __ _ ___ __ _ // / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_) // / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _ // /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_) // // _______..___________. ___ __ ___ __ .__ __. _______ .______ ______ ______ __ _______. // / || | / \ | |/ / | | | \ | | / _____| | _ \ / __ \ / __ \ | | / | // | (----``---| |----` / ^ \ | ' / | | | \| | | | __ | |_) | | | | | | | | | | | | (----` // \ \ | | / /_\ \ | < | | | . ` | | | |_ | | ___/ | | | | | | | | | | \ \ // .----) | | | / _____ \ | . \ | | | |\ | | |__| | | | | `--' | | `--' | | `----..----) | // |_______/ |__| /__/ \__\ |__|\__\ |__| |__| \__| \______| | _| \______/ \______/ |_______||_______/ /// /// @dev A contract which allows users to stake to farm tokens. /// /// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this /// repository: https://github.com/sushiswap/sushiswap. contract StakingPools is ReentrancyGuard { using FixedPointMath for FixedPointMath.uq192x64; using Pool for Pool.Data; using Pool for Pool.List; using SafeERC20 for IERC20; using SafeMath for uint256; using Stake for Stake.Data; event PendingGovernanceUpdated(address pendingGovernance); event GovernanceUpdated(address governance); event RewardRateUpdated(uint256 rewardRate); event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight); event PoolCreated(uint256 indexed poolId, IERC20 indexed token); event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount); event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount); event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount); /// @dev The token which will be minted as a reward for staking. IMintableERC20 public reward; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; address public pendingGovernance; /// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool /// will return an identifier of zero. mapping(IERC20 => uint256) public tokenPoolIds; /// @dev The context shared between the pools. Pool.Context private _ctx; /// @dev A list of all of the pools. Pool.List private _pools; /// @dev A mapping of all of the user stakes mapped first by pool and then by address. mapping(address => mapping(uint256 => Stake.Data)) private _stakes; constructor(IMintableERC20 _reward, address _governance) public { require(_governance != address(0), "StakingPools: governance address cannot be 0x0"); reward = _reward; governance = _governance; } /// @dev A modifier which reverts when the caller is not the governance. modifier onlyGovernance() { require(msg.sender == governance, "StakingPools: only governance"); _; } /// @dev Sets the governance. /// /// This function can only called by the current governance. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGovernance { require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } function acceptGovernance() external { require(msg.sender == pendingGovernance, "StakingPools: only pending governance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } /// @dev Sets the distribution reward rate. /// /// This will update all of the pools. /// /// @param _rewardRate The number of tokens to distribute per second. function setRewardRate(uint256 _rewardRate) external onlyGovernance { _updatePools(); _ctx.rewardRate = _rewardRate; emit RewardRateUpdated(_rewardRate); } /// @dev Creates a new pool. /// /// The created pool will need to have its reward weight initialized before it begins generating rewards. /// /// @param _token The token the pool will accept for staking. /// /// @return the identifier for the newly created pool. function createPool(IERC20 _token) external onlyGovernance returns (uint256) { require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool"); uint256 _poolId = _pools.length(); _pools.push( Pool.Data({ token: _token, totalDeposited: 0, rewardWeight: 0, accumulatedRewardWeight: FixedPointMath.uq192x64(0), lastUpdatedBlock: block.number }) ); tokenPoolIds[_token] = _poolId + 1; emit PoolCreated(_poolId, _token); return _poolId; } /// @dev Sets the reward weights of all of the pools. /// /// @param _rewardWeights The reward weights of all of the pools. function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance { require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch"); _updatePools(); uint256 _totalRewardWeight = _ctx.totalRewardWeight; for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); uint256 _currentRewardWeight = _pool.rewardWeight; if (_currentRewardWeight == _rewardWeights[_poolId]) { continue; } // FIXME _totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]); _pool.rewardWeight = _rewardWeights[_poolId]; emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]); } _ctx.totalRewardWeight = _totalRewardWeight; } /// @dev Stakes tokens into a pool. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _deposit(_poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); _withdraw(_poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function claim(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); } /// @dev Claims all rewards from a pool and then withdraws all staked tokens. /// /// @param _poolId the pool to exit from. function exit(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); _withdraw(_poolId, _stake.totalDeposited); } /// @dev Gets the rate at which tokens are minted to stakers for all pools. /// /// @return the reward rate. function rewardRate() external view returns (uint256) { return _ctx.rewardRate; } /// @dev Gets the total reward weight between all the pools. /// /// @return the total reward weight. function totalRewardWeight() external view returns (uint256) { return _ctx.totalRewardWeight; } /// @dev Gets the number of pools that exist. /// /// @return the pool count. function poolCount() external view returns (uint256) { return _pools.length(); } /// @dev Gets the token a pool accepts. /// /// @param _poolId the identifier of the pool. /// /// @return the token. function getPoolToken(uint256 _poolId) external view returns (IERC20) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.token; } /// @dev Gets the total amount of funds staked in a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the total amount of staked or deposited tokens. function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.totalDeposited; } /// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward weight. function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.rewardWeight; } /// @dev Gets the amount of tokens per block being distributed to stakers for a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward rate. function getPoolRewardRate(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.getRewardRate(_ctx); } /// @dev Gets the number of tokens a user has staked into a pool. /// /// @param _account The account to query. /// @param _poolId the identifier of the pool. /// /// @return the amount of deposited tokens. function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.totalDeposited; } /// @dev Gets the number of unclaimed reward tokens a user can claim from a pool. /// /// @param _account The account to get the unclaimed balance of. /// @param _poolId The pool to check for unclaimed rewards. /// /// @return the amount of unclaimed reward tokens a user has in a pool. function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx); } /// @dev Updates all of the pools. function _updatePools() internal { for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); } } /// @dev Stakes tokens into a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function _deposit(uint256 _poolId, uint256 _depositAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.add(_depositAmount); _stake.totalDeposited = _stake.totalDeposited.add(_depositAmount); _pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount); emit TokensDeposited(msg.sender, _poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount); _stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount); _pool.token.safeTransfer(msg.sender, _withdrawAmount); emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function _claim(uint256 _poolId) internal { Stake.Data storage _stake = _stakes[msg.sender][_poolId]; uint256 _claimAmount = _stake.totalUnclaimed; _stake.totalUnclaimed = 0; reward.mint(msg.sender, _claimAmount); emit TokensClaimed(msg.sender, _poolId, _claimAmount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } //SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; library FixedPointMath { uint256 public constant DECIMALS = 18; uint256 public constant SCALAR = 10**DECIMALS; struct uq192x64 { uint256 x; } function fromU256(uint256 value) internal pure returns (uq192x64 memory) { uint256 x; require(value == 0 || (x = value * SCALAR) / SCALAR == value); return uq192x64(x); } function maximumValue() internal pure returns (uq192x64 memory) { return uq192x64(uint256(-1)); } function add(uq192x64 memory self, uq192x64 memory value) internal pure returns (uq192x64 memory) { uint256 x; require((x = self.x + value.x) >= self.x); return uq192x64(x); } function add(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { return add(self, fromU256(value)); } function sub(uq192x64 memory self, uq192x64 memory value) internal pure returns (uq192x64 memory) { uint256 x; require((x = self.x - value.x) <= self.x); return uq192x64(x); } function sub(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { return sub(self, fromU256(value)); } function mul(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { uint256 x; require(value == 0 || (x = self.x * value) / value == self.x); return uq192x64(x); } function div(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) { require(value != 0); return uq192x64(self.x / value); } function cmp(uq192x64 memory self, uq192x64 memory value) internal pure returns (int256) { if (self.x < value.x) { return -1; } if (self.x > value.x) { return 1; } return 0; } function decode(uq192x64 memory self) internal pure returns (uint256) { return self.x / SCALAR; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import { IDetailedERC20 } from "./IDetailedERC20.sol"; interface IMintableERC20 is IDetailedERC20 { function mint(address _recipient, uint256 _amount) external; function burnFrom(address account, uint256 amount) external; function lowerHasMinted(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import { Math } from "@openzeppelin/contracts/math/Math.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { FixedPointMath } from "../math/FixedPointMath.sol"; import { IDetailedERC20 } from "../../interfaces/token/ERC20/IDetailedERC20.sol"; import "hardhat/console.sol"; /// @title Pool /// /// @dev A library which provides the Pool data struct and associated functions. library Pool { using FixedPointMath for FixedPointMath.uq192x64; using Pool for Pool.Data; using Pool for Pool.List; using SafeMath for uint256; struct Context { uint256 rewardRate; uint256 totalRewardWeight; } struct Data { IERC20 token; uint256 totalDeposited; uint256 rewardWeight; FixedPointMath.uq192x64 accumulatedRewardWeight; uint256 lastUpdatedBlock; } struct List { Data[] elements; } /// @dev Updates the pool. /// /// @param _ctx the pool context. function update(Data storage _data, Context storage _ctx) internal { _data.accumulatedRewardWeight = _data.getUpdatedAccumulatedRewardWeight(_ctx); _data.lastUpdatedBlock = block.number; } /// @dev Gets the rate at which the pool will distribute rewards to stakers. /// /// @param _ctx the pool context. /// /// @return the reward rate of the pool in tokens per block. function getRewardRate(Data storage _data, Context storage _ctx) internal view returns (uint256) { // console.log("get reward rate"); // console.log(uint(_data.rewardWeight)); // console.log(uint(_ctx.totalRewardWeight)); // console.log(uint(_ctx.rewardRate)); return _ctx.rewardRate.mul(_data.rewardWeight).div(_ctx.totalRewardWeight); } /// @dev Gets the accumulated reward weight of a pool. /// /// @param _ctx the pool context. /// /// @return the accumulated reward weight. function getUpdatedAccumulatedRewardWeight(Data storage _data, Context storage _ctx) internal view returns (FixedPointMath.uq192x64 memory) { if (_data.totalDeposited == 0) { return _data.accumulatedRewardWeight; } uint256 _elapsedTime = block.number.sub(_data.lastUpdatedBlock); if (_elapsedTime == 0) { return _data.accumulatedRewardWeight; } uint256 _rewardRate = _data.getRewardRate(_ctx); uint256 _distributeAmount = _rewardRate.mul(_elapsedTime); if (_distributeAmount == 0) { return _data.accumulatedRewardWeight; } FixedPointMath.uq192x64 memory _rewardWeight = FixedPointMath.fromU256(_distributeAmount).div(_data.totalDeposited); return _data.accumulatedRewardWeight.add(_rewardWeight); } /// @dev Adds an element to the list. /// /// @param _element the element to add. function push(List storage _self, Data memory _element) internal { _self.elements.push(_element); } /// @dev Gets an element from the list. /// /// @param _index the index in the list. /// /// @return the element at the specified index. function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; } /// @dev Gets the last element in the list. /// /// This function will revert if there are no elements in the list. ///ck /// @return the last element in the list. function last(List storage _self) internal view returns (Data storage) { return _self.elements[_self.lastIndex()]; } /// @dev Gets the index of the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the index of the last element. function lastIndex(List storage _self) internal view returns (uint256) { uint256 _length = _self.length(); return _length.sub(1, "Pool.List: list is empty"); } /// @dev Gets the number of elements in the list. /// /// @return the number of elements. function length(List storage _self) internal view returns (uint256) { return _self.elements.length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import { Math } from "@openzeppelin/contracts/math/Math.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { FixedPointMath } from "../math/FixedPointMath.sol"; import { IDetailedERC20 } from "../../interfaces/token/ERC20/IDetailedERC20.sol"; import { Pool } from "./Pool.sol"; import "hardhat/console.sol"; /// @title Stake /// /// @dev A library which provides the Stake data struct and associated functions. library Stake { using FixedPointMath for FixedPointMath.uq192x64; using Pool for Pool.Data; using SafeMath for uint256; using Stake for Stake.Data; struct Data { uint256 totalDeposited; uint256 totalUnclaimed; FixedPointMath.uq192x64 lastAccumulatedWeight; } function update( Data storage _self, Pool.Data storage _pool, Pool.Context storage _ctx ) internal { _self.totalUnclaimed = _self.getUpdatedTotalUnclaimed(_pool, _ctx); _self.lastAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx); } function getUpdatedTotalUnclaimed( Data storage _self, Pool.Data storage _pool, Pool.Context storage _ctx ) internal view returns (uint256) { FixedPointMath.uq192x64 memory _currentAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx); FixedPointMath.uq192x64 memory _lastAccumulatedWeight = _self.lastAccumulatedWeight; if (_currentAccumulatedWeight.cmp(_lastAccumulatedWeight) == 0) { return _self.totalUnclaimed; } uint256 _distributedAmount = _currentAccumulatedWeight.sub(_lastAccumulatedWeight).mul(_self.totalDeposited).decode(); return _self.totalUnclaimed.add(_distributedAmount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDetailedERC20 is IERC20 { function name() external returns (string memory); function symbol() external returns (string memory); function decimals() external returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../Domain.sol"; import "../../../interfaces/token/ERC20/IDetailedERC20.sol"; import "hardhat/console.sol"; // solhint-disable no-inline-assembly // solhint-disable not-rely-on-time // Data part taken out for building of contracts that receive delegate calls contract ERC20Data { /// @notice owner > balance mapping. mapping(address => uint256) public balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; string public name; string public symbol; uint256 public decimals; } contract ERC20 is ERC20Data, Domain { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) public { name = name_; symbol = symbol_; decimals = 18; } /// @notice Transfers `amount` tokens from `msg.sender` to `to`. /// @param to The address to move the tokens. /// @param amount of the tokens to move. /// @return (bool) Returns True if succeeded. function transfer(address to, uint256 amount) public returns (bool) { // If `amount` is 0, or `msg.sender` is `to` nothing happens if (amount != 0) { uint256 srcBalance = balanceOf[msg.sender]; require(srcBalance >= amount, "ERC20::transfer: balance too low"); if (msg.sender != to) { require(to != address(0), "ERC20::transfer: no zero address"); // Moved down so low balance calls safe some gas balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1 } } emit Transfer(msg.sender, to, amount); return true; } /// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`. /// @param from Address to draw tokens from. /// @param to The address to move the tokens. /// @param amount The token amount to move. /// @return (bool) Returns True if succeeded. function transferFrom( address from, address to, uint256 amount ) public returns (bool) { // If `amount` is 0, or `from` is `to` nothing happens if (amount != 0) { uint256 srcBalance = balanceOf[from]; require(srcBalance >= amount, "ERC20::transferFrom: balance too low"); if (from != to) { uint256 spenderAllowance = allowance[from][msg.sender]; // If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20). if (spenderAllowance != type(uint256).max) { require(spenderAllowance >= amount, "ERC20::transferFrom: allowance too low"); allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked } require(to != address(0), "ERC20::transferFrom: no zero address"); // Moved down so other failed calls safe some gas balanceOf[from] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1 } } emit Transfer(from, to, amount); return true; } /// @notice Approves `amount` from sender to be spend by `spender`. /// @param spender Address of the party that can draw from msg.sender's account. /// @param amount The maximum collective amount that `spender` can draw. /// @return (bool) Returns True if approved. function approve(address spender, uint256 amount) public returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparator(); } // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Approves `value` from `owner_` to be spend by `spender`. /// @param owner_ Address of the owner. /// @param spender The address of the spender that gets approved to draw from `owner_`. /// @param value The maximum collective amount that `spender` can draw. /// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner_ != address(0), "ERC20::permit: Owner cannot be 0"); require(block.timestamp < deadline, "ERC20: Expired"); require( ecrecover( _getDigest( keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline)) ), v, r, s ) == owner_, "ERC20::permit: Invalid Signature" ); allowance[owner_][spender] = value; emit Approval(owner_, spender, value); } } // SPDX-License-Identifier: MIT // Based on code and smartness by Ross Campbell and Keno // Uses immutable to store the domain separator to reduce gas usage // If the chain id changes due to a fork, the forked chain will calculate on the fly. pragma solidity 0.6.12; // solhint-disable no-inline-assembly contract Domain { bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"); // See https://eips.ethereum.org/EIPS/eip-191 string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; // solhint-disable var-name-mixedcase bytes32 private immutable _DOMAIN_SEPARATOR; uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID; /// @dev Calculate the DOMAIN_SEPARATOR function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256(abi.encode(DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this))); } constructor() public { uint256 chainId; assembly { chainId := chainid() } _DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId); } /// @dev Return the DOMAIN_SEPARATOR // It's named internal to allow making it public from the contract that uses it by creating a simple view function // with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. // solhint-disable-next-line func-name-mixedcase function _domainSeparator() internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); } function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) { digest = keccak256(abi.encodePacked(EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, _domainSeparator(), dataHash)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../libraries/tokens/ERC20/ERC20.sol"; contract MockERC20 is ERC20 { uint256 public totalSupply; constructor( string memory _name, string memory _symbol, uint256 _initialAmount ) public ERC20(_name, _symbol) { // Give the creator all initial tokens balanceOf[msg.sender] = _initialAmount; // Update total supply totalSupply = _initialAmount; } function mint(address account, uint256 amount) external { require(account != address(0), "MockERC20::mint: mint to the zero address"); totalSupply += amount; balanceOf[account] += amount; emit Transfer(address(0), account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./SushiToken.sol"; import "hardhat/console.sol"; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SushiSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SUSHI is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } // The SUSHI TOKEN! SushiToken public sushi; // Dev address. address public devaddr; // Block number when bonus SUSHI period ends. uint256 public bonusEndBlock; // SUSHI tokens created per block. uint256 public sushiPerBlock; // Bonus muliplier for early sushi makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SUSHI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( SushiToken _sushi, address _devaddr, uint256 _sushiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sushi = _sushi; devaddr = _devaddr; sushiPerBlock = _sushiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 }) ); } // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock)); } } // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sushi.mint(devaddr, sushiReward.div(10)); sushi.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SUSHI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); safeSushiTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); safeSushiTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); } else { sushi.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // SushiToken with Governance. contract SushiToken is ERC20("SushiToken", "SUSHI"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SUSHI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce"); require(now <= expiry, "SUSHI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IStakingPools { function reward() external view returns (IERC20); function rewardRate() external view returns (uint256); function totalRewardWeight() external view returns (uint256); function getPoolToken(uint256 _poolId) external view returns (IERC20); function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { BoringMath, BoringMath128 } from "./libraries/boring/BoringMath.sol"; import { BoringOwnable } from "./libraries/boring/BoringOwnable.sol"; import { BoringERC20, IERC20 } from "./libraries/boring/BoringERC20.sol"; import { SignedSafeMath } from "./libraries/math/SignedSafeMath.sol"; import { IRewarder } from "./interfaces/sushi/IRewarder.sol"; import { IMasterChef } from "./interfaces/sushi/IMasterChef.sol"; import "hardhat/console.sol"; interface IMigratorChef { // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. function migrate(IERC20 token) external returns (IERC20); } /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block. /// It is the only address with minting rights for SUSHI. /// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token /// that is deposited into the MasterChef V1 (MCV1) contract. /// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. contract MasterChefV2 is BoringOwnable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of SUSHI entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of SUSHI to distribute per block. struct PoolInfo { uint128 accSushiPerShare; uint64 lastRewardBlock; uint64 allocPoint; } /// @notice Address of MCV1 contract. IMasterChef public immutable MASTER_CHEF; /// @notice Address of SUSHI contract. IERC20 public immutable SUSHI; /// @notice The index of MCV2 master pool in MCV1. uint256 public immutable MASTER_PID; // @notice The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; /// @notice Info of each MCV2 pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MCV2 pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MCV2. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20; uint256 private constant ACC_SUSHI_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare); event LogInit(); /// @param _MASTER_CHEF The SushiSwap MCV1 contract address. /// @param _sushi The SUSHI token contract address. /// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract. constructor( IMasterChef _MASTER_CHEF, IERC20 _sushi, uint256 _MASTER_PID ) public { MASTER_CHEF = _MASTER_CHEF; SUSHI = _sushi; MASTER_PID = _MASTER_PID; } /// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI. /// Any balance of transaction sender in `dummyToken` is transferred. /// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives. /// @param dummyToken The address of the ERC-20 token to deposit into MCV1. function init(IERC20 dummyToken) external { uint256 balance = dummyToken.balanceOf(msg.sender); require(balance != 0, "MasterChefV2: Balance must exceed 0"); dummyToken.safeTransferFrom(msg.sender, address(this), balance); dummyToken.approve(address(MASTER_CHEF), balance); MASTER_CHEF.deposit(MASTER_PID, balance); emit LogInit(); } /// @notice Returns the number of MCV2 pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add( uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder ) public onlyOwner { uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push( PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 }) ); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set( uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite ) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); } /// @notice Set the `migrator` contract. Can only be called by the owner. /// @param _migrator The contract address to set. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } /// @notice Migrate LP token to another LP contract through the `migrator` contract. /// @param _pid The index of the pool. See `poolInfo`. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "MasterChefV2: no migrator set"); IERC20 _lpToken = lpToken[_pid]; uint256 bal = _lpToken.balanceOf(address(this)); _lpToken.approve(address(migrator), bal); IERC20 newLpToken = migrator.migrate(_lpToken); require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match"); lpToken[_pid] = newLpToken; } /// @notice View function to see pending SUSHI on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending SUSHI reward for a given user. function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint; accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply); } pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Calculates and returns the `amount` of SUSHI per block. function sushiPerBlock() public view returns (uint256 amount) { amount = uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) / MASTER_CHEF.totalAllocPoint(); } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint; pool.accSushiPerShare = pool.accSushiPerShare.add( (sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128() ); } pool.lastRewardBlock = block.number.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare); } } /// @notice Deposit LP tokens to MCV2 for SUSHI allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MCV2. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of SUSHI rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSushi; // Interactions if (_pendingSushi != 0) { SUSHI.safeTransfer(to, _pendingSushi); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount); } emit Harvest(msg.sender, pid, _pendingSushi); } /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and SUSHI rewards. function withdrawAndHarvest( uint256 pid, uint256 amount, address to ) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); user.amount = user.amount.sub(amount); // Interactions SUSHI.safeTransfer(to, _pendingSushi); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingSushi); } /// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract. function harvestFromMasterChef() public { MASTER_CHEF.deposit(MASTER_PID, 0); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; library SignedSafeMath { int256 private constant _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } function toUInt256(int256 a) internal pure returns (uint256) { require(a >= 0, "Integer < 0"); return uint256(a); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { BoringERC20, IERC20 } from "../../libraries/boring/BoringERC20.sol"; interface IMasterChef { using BoringERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } function poolInfo(uint256 pid) external view returns (IMasterChef.PoolInfo memory); function totalAllocPoint() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; }
@dev Gets the number of pools that exist. @return the pool count.
function poolCount() external view returns (uint256) { return _pools.length(); }
14,526,783
[ 1, 3002, 326, 1300, 434, 16000, 716, 1005, 18, 327, 326, 2845, 1056, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 2845, 1380, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 2463, 389, 27663, 18, 2469, 5621, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x79541c2bBA3bD425812796C7FaC6f84dAf04a917/sources/contracts/emr.sol
numberOfPatients++;
function addPatient ( string memory _info )public{ Patient memory currPat ; currPat.info=_info; PMap[_info]=currPat; }
7,077,931
[ 1, 2696, 951, 22834, 5828, 9904, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 225, 527, 22834, 1979, 261, 203, 3639, 533, 3778, 389, 1376, 203, 377, 262, 482, 95, 203, 3639, 29541, 1979, 3778, 4306, 22834, 274, 203, 3639, 4306, 22834, 18, 1376, 33, 67, 1376, 31, 203, 3639, 453, 863, 63, 67, 1376, 65, 33, 17016, 22834, 31, 203, 540, 203, 203, 203, 377, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; contract boleno { string public constant name = "Boleno"; // Token name string public constant symbol = "BLN"; // Boleno token symbol uint8 public constant decimals = 18; // Number of decimals uint256 public totalSupply = 10**25; // The initial supply (10 million) in base unit address public supplier; // Boleno supplier address uint public blnpereth = 50; // Price of 1 Ether in Bolenos by the supplier uint public bounty = 15; // Percentage of bounty program. Initiates with 15% bool public sale = false; // Is there an ongoing sale? bool public referral = false; // Is the referral program enabled? // Events event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); mapping (address => uint256) public balances; // Balances mapping(address => mapping (address => uint256)) allowed;// Record of allowances // Initialization function boleno() { supplier = msg.sender; // Supplier is contract creator balances[supplier] = totalSupply; // The initial supply goes to supplier } // For functions that require only supplier usage modifier onlySupplier { if (msg.sender != supplier) throw; _; } // Token transfer function transfer(address _to, uint256 _value) returns (bool success) { if (now < 1502755200 && msg.sender != supplier) throw;// Cannot trade until Tuesday, August 15, 2017 12:00:00 AM (End of ICO) if (balances[msg.sender] < _value) throw; // Does the spender have enough Bolenos to send? if (balances[_to] + _value < balances[_to]) throw; // Overflow? balances[msg.sender] -= _value; // Subtract the Bolenos from the sender's balance balances[_to] += _value; // Add the Bolenos to the recipient's balance Transfer(msg.sender, _to, _value); // Send Bolenos transfer event return true; // Return true to client } // Token transfer on your behalf (i.e. by contracts) function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (now < 1502755200 && _from != supplier) throw; // Cannot trade until Tuesday, August 15, 2017 12:00:00 AM (End of ICO) if (balances[_from] < _value) throw; // Does the spender have enough Bolenos to send? if(allowed[_from][msg.sender] < _value) throw; // Is the sender allowed to spend as much money on behalf of the spender? if (balances[_to] + _value < balances[_to]) throw; // Overflow? balances[_from] -= _value; // Subtract the Bolenos from the sender's balance allowed[_from][msg.sender] -= _value; // Update allowances record balances[_to] += _value; // Add the Bolenos to the recipient's balance Transfer(_from, _to, _value); // Send Bolenos transfer event return true; // Return true to client } // Allows someone (i.e a contract) to spend on your behalf multiple times up to a certain value. // If this function is called again, it overwrites the current allowance with _value. // Approve 0 to cancel previous approval function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; // Update allowances record Approval(msg.sender, _spender, _value); // Send approval event return true; // Return true to client } // Check how much someone approved you to spend on their behalf function allowance(address _owner, address _spender) returns (uint256 bolenos) { return allowed[_owner][_spender]; // Check the allowances record } // What is the Boleno balance of a particular person? function balanceOf(address _owner) returns (uint256 bolenos){ return balances[_owner]; } /* Crowdsale related functions */ // Referral bounty system function referral(address referrer) payable { if(sale != true) throw; // Is there an ongoing sale? if(referral != true) throw; // Is referral bounty allowed by supplier? if(balances[referrer] < 100**18) throw; // Make sure referrer already has at least 100 Bolenos uint256 bolenos = msg.value * blnpereth; // Determine amount of equivalent Bolenos to the Ethers received /* First give Bolenos to the purchaser */ uint256 purchaserBounty = (bolenos / 100) * (100 + bounty);// Add bounty to the purchased amount if(balances[supplier] < purchaserBounty) throw; // Does the supplier have enough BLN tokens to sell? if (balances[msg.sender] + purchaserBounty < balances[msg.sender]) throw; // Overflow? balances[supplier] -= purchaserBounty; // Subtract the Bolenos from the supplier's balance balances[msg.sender] += purchaserBounty; // Add the Bolenos to the buyer's balance Transfer(supplier, msg.sender, purchaserBounty); // Send Bolenos transfer event /* Then give Bolenos to the referrer */ uint256 referrerBounty = (bolenos / 100) * bounty; // Only the bounty percentage is added to the referrer if(balances[supplier] < referrerBounty) throw; // Does the supplier have enough BLN tokens to sell? if (balances[referrer] + referrerBounty < balances[referrer]) throw; // Overflow? balances[supplier] -= referrerBounty; // Subtract the Bolenos from the supplier's balance balances[referrer] += referrerBounty; // Add the Bolenos to the buyer's balance Transfer(supplier, referrer, referrerBounty); // Send Bolenos transfer event } // Set the number of BLNs sold per ETH (only by the supplier). function setbounty(uint256 newBounty) onlySupplier { bounty = newBounty; } // Set the number of BLNs sold per ETH (only by the supplier). function setblnpereth(uint256 newRate) onlySupplier { blnpereth = newRate; } // Trigger Sale (only by the supplier) function triggerSale(bool newSale) onlySupplier { sale = newSale; } // Transfer both supplier status and all held Boleno tokens supply to a different address (only supplier) function transferSupply(address newSupplier) onlySupplier { if (balances[newSupplier] + balances[supplier] < balances[newSupplier]) throw;// Overflow? uint256 supplyValue = balances[supplier]; // Determine current value of the supply balances[newSupplier] += supplyValue; // Add supply to new supplier balances[supplier] -= supplyValue; // Substract supply from old supplier Transfer(supplier, newSupplier, supplyValue); // Send Bolenos transfer event supplier = newSupplier; // Transfer supplier status } // Claim sale Ethers. Can be executed by anyone. function claimSale(){ address dao = 0xE6237a036366b8003AeD725E8001BD91890be03F;// Hardcoded address of the Bolenum private DAO dao.transfer(this.balance); // Send all collected Ethers to the address } // Fallback function. Used for buying Bolenos from supplier by simply sending Ethers to contract function () payable { if(sale != true) throw; // Is there an ongoing sale? uint256 bolenos = msg.value * blnpereth; // Determine amount of equivalent Bolenos to the Ethers received if(balances[supplier] < bolenos) throw; // Does the supplier have enough BLN tokens to sell? if (balances[msg.sender] + bolenos < balances[msg.sender]) throw; // Overflow? balances[supplier] -= bolenos; // Subtract the Bolenos the supplier's balance balances[msg.sender] += bolenos; // Add the Bolenos to the buyer's balance Transfer(supplier, msg.sender, bolenos); // Send Bolenos transfer event } }
Supplier is contract creator
supplier = msg.sender;
12,918,026
[ 1, 13254, 353, 6835, 11784, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 17402, 273, 1234, 18, 15330, 31, 4766, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import './TokenLifecycle.sol'; import "./DSWarp.sol"; /** * @title SalePrice * @author Tavit Ohanian * @notice Allows determination of discounted sale price of token purchase */ contract SalePrice is TokenLifecycle { using SafeMath for uint256; /** * @dev State definitions */ /// @dev ICO Price in units of tokens per ether /// @dev 5000 VMTs per Ether uint256 public constant PRICE = 5000; /// @dev Initial discount in units of tokens per ether /// @dev 20% initial discount on VMTs per Ether uint256 public constant INITIAL_DISCOUNT = 1000; /// @dev Days in token sale uint public constant SALE_PERIOD = 10; /// @dev Days discount is fixed at a specific level uint public constant DISCOUNT_PERIOD = 2; /// @dev No discount during last period uint public constant TOTAL_DISCOUNT_PERIODS = (SALE_PERIOD / DISCOUNT_PERIOD) - 1; /// @dev Uniform reduction of discount amount in units of ether uint256 public constant DISCOUNT_REDUCTION_AMOUNT = INITIAL_DISCOUNT / TOTAL_DISCOUNT_PERIODS; /// @dev Used to compute purchase price uint prevPeriod; uint currPeriod; uint256 price; // in units of ether /** * @notice rate how many token units a buyer gets per wei */ uint256 public rate; /** * @dev Event definitions */ /** * @notice token purchase event * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value wei paid for purchase * @param amount amount of tokens purchased */ event PriceChangePurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @dev Constructor */ /** * @notice SalePrice(uint256 _rate) * @param _rate base purchase rate. */ function SalePrice(uint256 _rate) public { require(_rate > 0); rate = _rate; prevPeriod = 0; currPeriod = 0; price = PRICE + INITIAL_DISCOUNT; // in ether units } /** * @dev Fallback function (if exists) */ /** * @dev External functions */ /** * @dev Public functions */ /** * @notice validPurchase() * @return true if sale is running and period has not expired */ function validPurchase() public view returns (bool) { bool _active = saleStart > 0 && currentTime() >= saleStart && (currentTime() - saleStart) < (SALE_PERIOD * 1 days); return _active; } /** * @notice salePrice() * @notice Calculate price in tokens per wei. * @notice Available at any token phase state. */ function salePrice() public returns (uint256) { // called only when running and purchase is valid currPeriod = (currentTime() - saleStart) / (DISCOUNT_PERIOD * 1 days); if (currPeriod > prevPeriod) { prevPeriod = currPeriod; if (price >= SafeMath.add(PRICE, DISCOUNT_REDUCTION_AMOUNT)) { price = price.sub(DISCOUNT_REDUCTION_AMOUNT); } else { price = PRICE; // latch at non-discounted price } } return price; } /** * @dev Administrative functions */ /** * @dev Internal functions */ /** * @notice currentTime() * @notice override to warp time for sale discount testing * @return block.timestamp */ function currentTime() internal view returns (uint) { return block.timestamp; } /** * @dev Private functions */ }
latch at non-discounted price
price = PRICE;
15,840,858
[ 1, 80, 505, 622, 1661, 17, 23650, 329, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 7734, 6205, 273, 10365, 1441, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xB52E41082a25b6FF9C632566890e7f8924099dDE/sources/LEAKS.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 Context { | | }:{ | | pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0; function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
2,957,271
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 203, 565, 571, 571, 3639, 289, 18611, 3639, 571, 571, 203, 203, 683, 9454, 18035, 560, 273, 20, 18, 28, 18, 2163, 1545, 20, 18, 28, 18, 2163, 1545, 20, 18, 28, 18, 20, 411, 20, 18, 29, 18, 20, 31, 203, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 745, 892, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.00; // import "github.com/oraclize/ethereum-api/oraclizeAPI.sol"; contract gambling0 { uint lottery = 1 ether; address payable creater; uint maxRange = 100; uint pool = 0; bool lock = false; uint win = 0; mapping(uint => address payable[]) list; constructor() public { //oraclize_setProof(proofType_Ledger); creater = msg.sender; } modifier unlock(){ require(lock == false); _; } function bet(uint num) public payable unlock { require(msg.value >= lottery); list[num % maxRange].push(msg.sender); pool += lottery; } modifier onlyCreater() { require(msg.sender == creater); _; } /* function __callback(bytes32 _queryId, string _result, bytes _proof) { require(msg.sender != oraclize_cbAddress()); if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) { } else { uint win = uint(keccak256(_result)) % maxRange; // this is an efficient way to get the uint out in the [0, maxRange-1] range emit newRandomNumber_uint(win); // this is the resulting random number (uint) for(uint i = 0; i < list[win].length; i ++) { list[win][i].transfer(address(this).balance / list[win].length); } selfdestruct(creater); } } */ function endd() public onlyCreater { lock = true; // uint N = 7; // number of random bytes we want the datasource to return // uint delay = 20; // number of seconds to wait before the execution takes place // uint callbackGas = 200000; // amount of gas we want Oraclize to set for the callback function // bytes32 queryId = oraclize_newRandomDSQuery(delay, N, callbackGas); // this function internally generates the correct oraclize_query and returns its queryId bytes32 source = keccak256(abi.encodePacked(now, block.coinbase, creater)); win = uint(source) % maxRange; // this is an efficient way to get the uint out in the [0, maxRange-1] range block.coinbase.transfer(address(this).balance / 99); for(uint i = 0; i < list[win].length; i ++) { list[win][i].transfer(address(this).balance / list[win].length); } creater.transfer(address(this).balance); lock = false; pool = 0; } function getwin() public view returns(uint) { return win; } function des() public onlyCreater { selfdestruct(creater); } function getMoneyNum() public view returns(uint) { return pool; } }
this is an efficient way to get the uint out in the [0, maxRange-1] range
uint win = uint(keccak256(_result)) % maxRange;
1,819,733
[ 1, 2211, 353, 392, 14382, 4031, 358, 336, 326, 2254, 596, 316, 326, 306, 20, 16, 943, 2655, 17, 21, 65, 1048, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2254, 5657, 273, 2254, 12, 79, 24410, 581, 5034, 24899, 2088, 3719, 738, 943, 2655, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@chainlink/contracts/src/v0.8/interfaces/KeeperCompatibleInterface.sol"; contract onlineStore is KeeperCompatibleInterface, Ownable { address kovanKeeperRegistryAddress = 0x4Cb093f226983713164A62138C3F718A5b595F73; IERC20 deSocialNetToken = IERC20(0xAe0f650F39B943F738a790519C3556bf6f8C92F1); //adress of desocialNet token modifier onlyKeeper() { require(msg.sender == kovanKeeperRegistryAddress); _; } uint256 public lastCheckIn = block.timestamp; uint256 public checkInTimeInterval = 864000; //default to six months address public nextOwner; uint256 public massivePurchaseTokenPrice =0.001*10**18; // 1 Million tokens is 1 Ether uint256 public largePurchaseTokenPrice = 0.00015*10**18; // 100,000 tokens is 0.15 Ether uint256 public mediumPurchaseTokenPrice = 0.00004*10**18; // 20,0000 tokens is 0.04 Ether uint256 public smallPurchaseTokenPrice = 0.000025*10**18; // 10,0000 tokens is 0.025 Ether function buyMassiveTokens() public payable{ // how many tokens they want to purchase require(deSocialNetToken.balanceOf(address(this)) >= 1000000*10**10,"Not Enought Tokens in Contract"); // require this contract to have at least 1,000,000 tokens before executing require(msg.value >= massivePurchaseTokenPrice,"Send the right amount of eth"); // there is a bug when calling the contract through moralis that the msg.value did not equal required even though msg.value was correct. deSocialNetToken.transfer(msg.sender, 1000000*10**18); // send a million tokens. } function buyLargeTokens() public payable{ // how many tokens they want to purchase require(deSocialNetToken.balanceOf(address(this)) >= 100000*10**10,"Not Enought Tokens in Contract"); // require this contract to have at least 1,000,000 tokens before executing require(msg.value >= largePurchaseTokenPrice,"Send the right amount of eth"); // require this contract to have at least 1,000,000 tokens before executing deSocialNetToken.transfer(msg.sender, 100000*10**18); // send 100,0000 tokens. } function buyMediumTokens() public payable{ // how many tokens they want to purchase require(deSocialNetToken.balanceOf(address(this)) >= 20000*10**10,"Not Enought Tokens in Contract"); // require this contract to have at least 1,000,000 tokens before executing require(msg.value >= mediumPurchaseTokenPrice,"Send the right amount of eth"); // require this contract to have at least 1,000,000 tokens before executing deSocialNetToken.transfer(msg.sender, 20000*10**18); // send 20,0000 tokens. } function buySmallTokens() public payable{ // how many tokens they want to purchase require(deSocialNetToken.balanceOf(address(this)) >= 10000*10**10,"Not Enought Tokens in Contract"); // require this contract to have at least 1,000,000 tokens before executing require(msg.value >= smallPurchaseTokenPrice,"Send the right amount of eth"); // require this contract to have at least 1,000,000 tokens before executing deSocialNetToken.transfer(msg.sender, 10000*10**18); // send 10,0000 tokens. } function withdrawErc20(IERC20 token) public onlyOwner{ //withdraw all ERC-20 that get accidently sent since this is an only ether store. require(token.transfer(msg.sender, token.balanceOf(address(this))), "Transfer failed"); } function withdraw(uint amount) public onlyOwner returns(bool) { require(amount <= address(this).balance); payable(msg.sender).transfer(amount); //if the owner send to sender return true; } function setMassiveStorePrice(uint256 newPrice) public onlyOwner { require (newPrice <= massivePurchaseTokenPrice*2, "too high price"); // just in case you fat finger a number and accidently set a number too high or too low require (newPrice >= massivePurchaseTokenPrice/2, "too low price"); massivePurchaseTokenPrice = newPrice; } function setLargeStorePrice(uint256 newPrice) public onlyOwner { require (newPrice <= largePurchaseTokenPrice*2, "too high price"); // just in case you fat finger a number and accidently set a number too high or too low require (newPrice >= largePurchaseTokenPrice/2, "too low price"); largePurchaseTokenPrice = newPrice; } function setMediumStorePrice(uint256 newPrice) public onlyOwner { require (newPrice <= mediumPurchaseTokenPrice*2, "too high price"); // just in case you fat finger a number and accidently set a number too high or too low require (newPrice >= mediumPurchaseTokenPrice/2, "too low price"); mediumPurchaseTokenPrice = newPrice; } function setsmallStorePrice(uint256 newPrice) public onlyOwner { require (newPrice <= smallPurchaseTokenPrice*2, "too high price"); // just in case you fat finger a number and accidently set a number too high or too low require (newPrice >= smallPurchaseTokenPrice/2, "too low price"); smallPurchaseTokenPrice = newPrice; } function changeInheritance(address newInheritor) public onlyOwner { nextOwner = newInheritor; } function ownerCheckIn() public onlyOwner { lastCheckIn = block.timestamp; } function changeCheckInTime(uint256 newCheckInTimeInterval) public onlyOwner { checkInTimeInterval = newCheckInTimeInterval; // let owner change check in case he know he will be away for a while. } function passDownInheritance() internal { transferOwnership( nextOwner); } function checkUpkeep(bytes calldata /* checkData */) external override returns (bool upkeepNeeded, bytes memory /* performData */) { //upkeepNeeded = (block.timestamp > (lastCheck + 5184000)); // We don't use the checkData in this example. The checkData is defined when the Upkeep was registered. return (block.timestamp > (lastCheckIn + checkInTimeInterval), bytes("")); // make sure to check in at least once every 6 months } function performUpkeep(bytes calldata /* performData */) external onlyKeeper override { passDownInheritance(); } }
10,0000 tokens is 0.025 Ether
uint256 public smallPurchaseTokenPrice = 0.000025*10**18;
12,737,210
[ 1, 2163, 16, 2787, 2430, 353, 374, 18, 20, 2947, 512, 1136, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5264, 23164, 1345, 5147, 273, 374, 18, 2787, 2947, 14, 2163, 636, 2643, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0xCa2cFE9cA7179eC3Aa59d047afbed3441D055109/sources/Master.sol
* @title SafeMath @dev Math operations with safety checks that revert on error/
library SafeMath { pragma solidity >=0.5.17 <0.8.0; function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
11,473,781
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 15226, 603, 555, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 18, 4033, 411, 20, 18, 28, 18, 20, 31, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 70, 1648, 279, 1769, 203, 3639, 2254, 5034, 276, 273, 279, 300, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 2 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @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/token/ERC20/SafeERC20.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"); } } } // File: contracts/Vault/BaseStrategy.sol struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; bool enforceChangeLimit; uint256 profitLimitRatio; uint256 lossLimitRatio; address customCheck; } interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function apiVersion() external pure returns (string memory); function keeper() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } /** * @title DeFi Yield Technology Base Strategy * @author DeFi Yield Technology * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.0.1"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards DeFi Yield Technology TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of DeFi Yield Technology ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in DeFi Yield Technology Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0), "The strategist's new address cannot be the same as the ZERO ADDRESS!"); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0), "The keeper's new address cannot be the same as the ZERO ADDRESS!"); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0), "The reward's new address cannot be the same as the ZERO ADDRESS!"); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by DeFi Yield Technology). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by DeFi Yield Technology). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/vladZokyo/DeFiYieldTechnology/blob/dev/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault), "Only the vault can call migrate strategy!"); require(BaseStrategy(_newStrategy).vault() == vault, "New strategy vault must be equalt to old vault!"); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } abstract contract BaseStrategyInitializable is BaseStrategy { bool public isOriginal = true; event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) {} function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function clone(address _vault) external returns (address) { require(isOriginal, "!clone"); return this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper); emit Cloned(newStrategy); } } // File: contracts/Strategies/StrategyGenLevCompFarm/Interfaces/IStrategy.sol interface IStrategy { function vault() external view returns (address); function want() external view returns (address); function strategist() external view returns (address); function useLoanTokens( bool deficit, uint256 amount, uint256 repayAmount ) external; } // File: contracts/Strategies/GeneralInterfaces/DyDx/ISoloMargin.sol library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } interface ISoloMargin { struct OperatorArg { address operator1; bool trusted; } function ownerSetSpreadPremium(uint256 marketId, Decimal.D256 memory spreadPremium) external; function getIsGlobalOperator(address operator1) external view returns (bool); function getMarketTokenAddress(uint256 marketId) external view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) external; function getAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) external view returns (address); function getMarketInterestSetter(uint256 marketId) external view returns (address); function getMarketSpreadPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getNumMarkets() external view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) external returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) external; function ownerSetLiquidationSpread(Decimal.D256 memory spread) external; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) external; function getIsLocalOperator(address owner, address operator1) external view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) external view returns (Types.Par memory); function ownerSetMarginPremium(uint256 marketId, Decimal.D256 memory marginPremium) external; function getMarginRatio() external view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) external view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) external view returns (bool); function getRiskParams() external view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) external view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function renounceOwnership() external; function getMinBorrowedValue() external view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) external; function getMarketPrice(uint256 marketId) external view returns (address); function owner() external view returns (address); function isOwner() external view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) external returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) external; function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external; function getMarketWithInfo(uint256 marketId) external view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) external; function getLiquidationSpread() external view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) external view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) external view returns (Types.TotalPar memory); function getLiquidationSpreadForPair(uint256 heldMarketId, uint256 owedMarketId) external view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) external view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) external view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) external view returns (uint8); function getEarningsRate() external view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) external; function getRiskLimits() external view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) external view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) external; function ownerSetGlobalOperator(address operator1, bool approved) external; function transferOwnership(address newOwner) external; function getAdjustedAccountValues(Account.Info memory account) external view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) external view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) external view returns (Interest.Rate memory); } // File: contracts/Strategies/GeneralInterfaces/DyDx/DydxFlashLoanBase.sol contract DydxFlashloanBase { using SafeMath for uint256; function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } // File: contracts/Strategies/GeneralInterfaces/DyDx/ICallee.sol /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { // ============ Public Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } // File: contracts/Strategies/StrategyGenLevCompFarm/1.sol // Vault. // DyDx. contract FlashLoanPlugin is ICallee, DydxFlashloanBase { using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 internal want; address internal SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; IStrategy internal strategy; bool internal awaitingFlash = false; uint256 public dyDxMarketId; // @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan); constructor (address _strategy) public { strategy = IStrategy(_strategy); want = IERC20(strategy.want()); want.approve(_strategy, uint256(-1)); want.safeApprove(SOLO, type(uint256).max); } function updateMarketId() external { require(msg.sender == address(strategy)); _setMarketIdFromTokenAddress(); } function setSOLO(address _solo) external { require(msg.sender == address(strategy)); want.approve(SOLO, 0); SOLO = _solo; want.approve(SOLO, uint256(-1)); } // Flash loan DXDY // amount desired is how much we are willing for position to change function doDyDxFlashLoan( bool _deficit, uint256 _amountDesired ) external returns(uint256) { require(msg.sender == address(strategy), "not strategy!"); uint256 amount = _amountDesired; ISoloMargin solo = ISoloMargin(SOLO); // Not enough want in DyDx. So we take all we can. uint256 amountInSolo = want.balanceOf(SOLO); if (amountInSolo < amount) { amount = amountInSolo; } // we need to overcollateralise on way back uint256 repayAmount = amount.add(2); bytes memory data = abi.encode(_deficit, amount, repayAmount); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(dyDxMarketId, amount); operations[1] = _getCallAction( // Encode custom data for callFunction data ); operations[2] = _getDepositAction(dyDxMarketId, repayAmount); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); emit Leverage(_amountDesired, amount, _deficit, SOLO); return amount; } function _setMarketIdFromTokenAddress() internal { ISoloMargin solo = ISoloMargin(SOLO); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == address(want)) { dyDxMarketId = i; return; } } revert("No marketId found for provided token"); } function callFunction( address sender, Account.Info memory account, bytes memory data ) external override { (bool deficit, uint256 amount, uint256 repayAmount) = abi.decode(data, (bool, uint256, uint256)); require(msg.sender == SOLO, "NOT_SOLO"); _loanLogic(deficit, amount, repayAmount); } //called by flash loan function _loanLogic( bool deficit, uint256 amount, uint256 repayAmount ) internal { want.transfer(address(strategy), want.balanceOf(address(this))); strategy.useLoanTokens(deficit, amount, repayAmount); } }
* @title ICallee @author dYdX Interface that Callees for Solo must implement in order to ingest data./ ============ Public Functions ============
interface ICallee { function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; }
65,270
[ 1, 2871, 287, 11182, 225, 302, 61, 72, 60, 6682, 716, 3596, 298, 281, 364, 348, 12854, 1297, 2348, 316, 1353, 358, 29105, 501, 18, 19, 422, 1432, 631, 7224, 15486, 422, 1432, 631, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 3005, 11182, 288, 203, 203, 565, 445, 745, 2083, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 6590, 18, 966, 3778, 2236, 966, 16, 203, 3639, 1731, 3778, 501, 203, 565, 262, 3903, 31, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xDda46bF18eeb3E06E2F12975A3A184e40581A72f/sources/contracts/vendors/IRateProvider.sol
* @title IRateProvider @notice This interface ensure compatibility with Balancer's Metastable pools, the getRate() method is used as the pool rate. This reduces arbitrages whenever the swETH rate increases from a repricing event./
interface IRateProvider { function getRate() external view returns (uint256); pragma solidity 0.8.16; }
3,094,213
[ 1, 45, 4727, 2249, 225, 1220, 1560, 3387, 8926, 598, 605, 5191, 1807, 21604, 689, 429, 16000, 16, 326, 4170, 340, 1435, 707, 353, 1399, 487, 326, 2845, 4993, 18, 1220, 30568, 10056, 86, 1023, 17334, 326, 1352, 1584, 44, 4993, 7033, 3304, 628, 279, 8480, 14774, 871, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 4727, 2249, 288, 203, 225, 445, 4170, 340, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 2313, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xB20700BA8001E94948cFC21fA024eb6EB65ec45c/sources/Destinations.sol
Friday, June 23, 2023 15:00:00 GMT+01:00
saleStartTime = 1687528800;
3,564,964
[ 1, 42, 1691, 528, 16, 804, 7556, 10213, 16, 26599, 23, 4711, 30, 713, 30, 713, 21706, 15, 1611, 30, 713, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 272, 5349, 13649, 273, 2872, 28, 5877, 22, 5482, 713, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2017-2018 Phillip A. Elsasser Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.24; import "./MarketContractOraclize.sol"; import "./oraclizeAPI.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; contract OracleHubOraclize is usingOraclize, Ownable { mapping(address => OraclizeQuery) contractAddressToOraclizeQuery; mapping(bytes32 => OraclizeQuery) queryIDToOraclizeQuery; address public marketContractFactoryAddress; mapping(bytes32 => bool) public validQueryIDs; uint constant public QUERY_CALLBACK_GAS = 160000; /// @dev all needed pieces of an oraclize query. struct OraclizeQuery { address marketContractAddress; string dataSource; string query; } event OraclizeQueryRequested(address indexed marketContract, bytes32 indexed queryId); /// @dev creates our OracleHub /// @param contractFactoryAddress address of our MarketContractFactory constructor(address contractFactoryAddress) public payable { oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); marketContractFactoryAddress = contractFactoryAddress; } /* // EXTERNAL METHODS */ /// @dev allows us to withdraw eth as the owner of this contract /// @param sendTo address of where to send ETH /// @param amount amount of ETH (in baseUnits) function withdrawEther(address sendTo, uint256 amount) external onlyOwner returns (bool) { return sendTo.send(amount); } /// @notice allows a user to request an extra query to oracle in order to push the contract into /// settlement. A user may call this as many times as they like, since they are the ones paying for /// the call to our oracle and post processing. This is useful for both a failsafe and as a way to /// settle a contract early if a price cap or floor has been breached. function requestOnDemandQuery(address marketContractAddress) external payable { OraclizeQuery storage oraclizeQuery = contractAddressToOraclizeQuery[marketContractAddress]; uint cost = oraclize_getPrice(oraclizeQuery.dataSource, QUERY_CALLBACK_GAS); require(msg.value >= cost, "requires a higher cost"); // user must pay enough to cover query and callback bytes32 queryId = oraclize_query( oraclizeQuery.dataSource, oraclizeQuery.query, QUERY_CALLBACK_GAS ); require(queryId != 0); validQueryIDs[queryId] = true; queryIDToOraclizeQuery[queryId] = oraclizeQuery; emit OraclizeQueryRequested(marketContractAddress, queryId); } /// @dev allows for the owner to set a factory address that is then allowed the priviledge of creating /// queries. function setFactoryAddress(address contractFactoryAddress) external onlyOwner { marketContractFactoryAddress = contractFactoryAddress; } /// @dev called by our factory to create the needed initial query for a new MarketContract /// @param marketContractAddress - address of the newly created MarketContract /// @param oracleDataSource a data-source such as "URL", "WolframAlpha", "IPFS" /// see http://docs.oraclize.it/#ethereum-quick-start-simple-query /// @param oracleQuery see http://docs.oraclize.it/#ethereum-quick-start-simple-query for examples function requestQuery( address marketContractAddress, string oracleDataSource, string oracleQuery, uint expiration ) external onlyFactory { OraclizeQuery storage oraclizeQuery = contractAddressToOraclizeQuery[marketContractAddress]; oraclizeQuery.marketContractAddress = marketContractAddress; oraclizeQuery.dataSource = oracleDataSource; oraclizeQuery.query = oracleQuery; bytes32 queryId = oraclize_query( expiration, oracleDataSource, oracleQuery, QUERY_CALLBACK_GAS ); require(queryId != 0); validQueryIDs[queryId] = true; queryIDToOraclizeQuery[queryId] = oraclizeQuery; // save query struct for later recall on callback. emit OraclizeQueryRequested(marketContractAddress, queryId); } /// @notice only public for callbacks from oraclize, do not call /// @param queryID of the returning query, this should match our own internal mapping /// @param result query to be processed /// @param proof result proof function __callback(bytes32 queryID, string result, bytes proof) public { require(msg.sender == oraclize_cbAddress()); require(validQueryIDs[queryID]); // At expiration or early settlement. OraclizeQuery memory oraclizeQuery = queryIDToOraclizeQuery[queryID]; MarketContractOraclize marketContract = MarketContractOraclize(oraclizeQuery.marketContractAddress); uint price = parseInt(result, marketContract.PRICE_DECIMAL_PLACES()); marketContract.oracleCallBack(price); delete validQueryIDs[queryID]; proof; // silence compiler warnings } /* // MODIFIERS */ /// @dev only callable by the designated factory! modifier onlyFactory() { require(msg.sender == marketContractFactoryAddress); _; } }
@notice allows a user to request an extra query to oracle in order to push the contract into settlement. A user may call this as many times as they like, since they are the ones paying for the call to our oracle and post processing. This is useful for both a failsafe and as a way to settle a contract early if a price cap or floor has been breached.
function requestOnDemandQuery(address marketContractAddress) external payable { OraclizeQuery storage oraclizeQuery = contractAddressToOraclizeQuery[marketContractAddress]; uint cost = oraclize_getPrice(oraclizeQuery.dataSource, QUERY_CALLBACK_GAS); bytes32 queryId = oraclize_query( oraclizeQuery.dataSource, oraclizeQuery.query, QUERY_CALLBACK_GAS ); require(queryId != 0); validQueryIDs[queryId] = true; queryIDToOraclizeQuery[queryId] = oraclizeQuery; emit OraclizeQueryRequested(marketContractAddress, queryId); }
12,885,457
[ 1, 5965, 87, 279, 729, 358, 590, 392, 2870, 843, 358, 20865, 316, 1353, 358, 1817, 326, 6835, 1368, 26319, 806, 18, 225, 432, 729, 2026, 745, 333, 487, 4906, 4124, 487, 2898, 3007, 16, 3241, 2898, 854, 326, 5945, 8843, 310, 364, 326, 745, 358, 3134, 20865, 471, 1603, 4929, 18, 1220, 353, 5301, 364, 3937, 279, 2321, 4626, 471, 487, 279, 4031, 358, 444, 5929, 279, 6835, 11646, 309, 279, 6205, 3523, 578, 6346, 711, 2118, 324, 266, 2004, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 590, 1398, 25461, 1138, 12, 2867, 13667, 8924, 1887, 13, 3903, 8843, 429, 288, 203, 3639, 531, 354, 830, 554, 1138, 2502, 578, 10150, 554, 1138, 273, 6835, 1887, 774, 51, 354, 830, 554, 1138, 63, 27151, 8924, 1887, 15533, 203, 3639, 2254, 6991, 273, 578, 10150, 554, 67, 588, 5147, 12, 280, 10150, 554, 1138, 18, 892, 1830, 16, 17089, 67, 30312, 67, 43, 3033, 1769, 203, 203, 3639, 1731, 1578, 843, 548, 273, 578, 10150, 554, 67, 2271, 12, 203, 5411, 578, 10150, 554, 1138, 18, 892, 1830, 16, 203, 5411, 578, 10150, 554, 1138, 18, 2271, 16, 203, 5411, 17089, 67, 30312, 67, 43, 3033, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 2271, 548, 480, 374, 1769, 203, 3639, 923, 1138, 5103, 63, 2271, 548, 65, 273, 638, 31, 203, 3639, 843, 734, 774, 51, 354, 830, 554, 1138, 63, 2271, 548, 65, 273, 578, 10150, 554, 1138, 31, 203, 3639, 3626, 531, 354, 830, 554, 1138, 11244, 12, 27151, 8924, 1887, 16, 843, 548, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * :::::::::::::::::::::::::::::::::::::::::::: * :::::::::::::::::::::::::::::::::::::::::::::::: * :::::::::::::::::::::::::::::::::::::::::::::::: * ::::::::::::NNNNNNNNN:::::::NNNNNNNN:::::::::::: * ::::::::::::NNNNNNNNNN::::::NNNNNNNN:::::::::::: * ::::::::::::NNNNNNNNNNN:::::NNNNNNNN:::::::::::: * ::::::::::::NNNNNNNNNNNN::::NNNNNNNN:::::::::::: * ::::::::::::NNNNNNNNNNNNN:::NNNNNNNN:::::::::::: * ::::::::::::NNNNNNNNNNNNNN::NNNNNNNN:::::::::::: * ::::::::::::NNNNNNNN:NNNNNN:NNNNNNNN:::::::::::: * ::::::::::::NNNNNNNN::NNNNNNNNNNNNNN:::::::::::: * ::::::::::::NNNNNNNN:::NNNNNNNNNNNNN:::::::::::: * ::::::::::::NNNNNNNN::::NNNNNNNNNNNN:::::::::::: * ::::::::::::NNNNNNNN:::::NNNNNNNNNNN:::::::::::: * ::::::::::::NNNNNNNN::::::NNNNNNNNNN:::::::::::: * ::::::::::::NNNNNNNN:::::::NNNNNNNNN:::::::::::: * :::::::::::::::::::::::::::::::::::::::::::::::: * :::::::::::::::::::::::::::::::::::::::::::::::: * :::::::::::::::::::::::::::::::::::::::::::: * * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: contracts/interface/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: contracts/interface/IERC721Receiver.sol /** * @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/interface/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/util/Context.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 Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } // File: contracts/util/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } } // File: contracts/standard/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/core/NiftyEntity.sol /** * @dev Authenticator of state mutating operations for Nifty Gateway contracts. * * addresses for stateful operations. * * Rinkeby: 0xCefBf44ff649B6E0Bc63785699c6F1690b8cF73b * Mainnet: 0x6e53130dDfF21E3BC963Ee902005223b9A202106 */ contract NiftyEntity { // Address of {NiftyRegistry} contract. address internal immutable niftyRegistryContract = 0x6e53130dDfF21E3BC963Ee902005223b9A202106; //Mainnet /** * @dev Determines whether accounts are allowed to invoke state mutating operations on child contracts. */ modifier onlyValidSender() { NiftyRegistry niftyRegistry = NiftyRegistry(niftyRegistryContract); bool isValid = niftyRegistry.isValidNiftySender(msg.sender); require(isValid, "NiftyEntity: Invalid msg.sender"); _; } /** * @dev Points to the repository of authenticated addresses. */ constructor() {} } /** * @dev Defined to mediate interaction with externally deployed {NiftyRegistry} dependency. */ interface NiftyRegistry { function isValidNiftySender(address sending_key) external view returns (bool); } // File: contracts/core/ERC721.sol /** * @dev Nifty Gateway implementation of Non-Fungible Token Standard. */ contract ERC721 is NiftyEntity, Context, ERC165, IERC721, IERC721Metadata { // Tracked individual instance spawned by {BuilderShop} contract. uint immutable public _id; // Number of distinct NFTs housed in this contract. uint immutable public _typeCount; // Intial receiver of all newly minted NFTs. address immutable public _defaultOwner; // Component(s) of 'tokenId' calculation. uint immutable internal topLevelMultiplier; uint immutable internal midLevelMultiplier; // Token name. string private _name; // Token symbol. string private _symbol; // Token artifact location. string private _baseURI; // Mapping from Nifty type to name of token. mapping(uint256 => string) private _niftyTypeName; // Mapping from Nifty type to IPFS hash of canonical artifcat file. mapping(uint256 => string) private _niftyTypeIPFSHashes; // Mapping from token ID to owner address. mapping (uint256 => address) internal _owners; // Mapping owner address to token count, by aggregating all _typeCount NFTs in the contact. mapping (address => uint256) internal _balances; // Mapping from token ID to approved address. mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals. mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the token collection. */ constructor() NiftyEntity() { _id = 2; _typeCount = 3; _symbol = "ARSHAM"; _name = "Eroding and Reforming Digital Sculptures"; _baseURI = "https://api.niftygateway.com/arsham/"; _defaultOwner = 0xE052113bd7D7700d623414a0a4585BCaE754E9d5; midLevelMultiplier = 10000; topLevelMultiplier = 200000000; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the link to artificat location for a given token by 'tokenId'. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query. * @return The location where the artifact assets are stored. */ function tokenURI(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory tokenIdStr = Strings.toString(tokenId); return string(abi.encodePacked(_baseURI, tokenIdStr)); } /** * @dev Determine which NFT in the contract (_typeCount) is associated * with this 'tokenId'. */ function _getNiftyTypeId(uint256 tokenId) internal view returns (uint256) { return (tokenId - topLevelMultiplier) / midLevelMultiplier; } /** * @dev Returns the Name for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenName(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: Name query for nonexistent token"); uint256 niftyType = _getNiftyTypeId(tokenId); return _niftyTypeName[niftyType]; } /** * @dev Internal function to set the token IPFS hash for a nifty type. * @param niftyType uint256 ID component of the token to set its IPFS hash * @param ipfs_hash string IPFS link to assign */ function _setTokenIPFSHashNiftyType(uint256 niftyType, string memory ipfs_hash) internal { require(bytes(_niftyTypeIPFSHashes[niftyType]).length == 0, "ERC721Metadata: IPFS hash already set"); _niftyTypeIPFSHashes[niftyType] = ipfs_hash; } /** * @dev Internal function to set the name for a nifty type. * @param niftyType uint256 of nifty type name to be set * @param nifty_type_name name of nifty type */ function _setNiftyTypeName(uint256 niftyType, string memory nifty_type_name) internal { _niftyTypeName[niftyType] = nifty_type_name; } /** * @dev Base URI for computing {tokenURI}. */ function _setBaseURI(string memory baseURI_) internal { _baseURI = baseURI_; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (isContract(to)) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev 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; } } // File: contracts/standard/ERC721Burnable.sol /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // File: contracts/interface/IDateTime.sol /** * */ interface IDateTime { function getYear(uint timestamp) external view virtual returns (uint16); function getHour(uint timestamp) external view virtual returns (uint8); function getWeekday(uint timestamp) external view virtual returns (uint8); } // File: contracts/core/NiftyBuilderInstance.sol /** * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX .*** XXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ,********* XXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXX *************** XXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXX .******************* XXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXX *********** ********** XXXXXXXX * XXXXXXXXXXXXXXXXXXXX *********** *********** XXXXXX * XXXXXXXXXXXXXXXXXX *********** *************** XXX * XXXXXXXXXXXXXXXX *********** **** ********* XX * XXXXXXXXXXXXXXXX ********* *** *** ********* X * XXXXXXXXXXXXXXXX ********** ***** *********** XXX * XXXXXXXXXXXX /////.************* *********** XXXX * XXXXXXXXX /////////...*********** ************ XXXXXX * XXXXXXX/ ///////////..... ///////// /////////// XXXXXXXX * XXXXXX / //////........./////////////////// XXXXXXXXXX * XXXXXXXXXX .///////...........////////////// XXXXXXXXXXXXX * XXXXXXXXX .///////.....//..//// ///////// XXXXXXXXXXXXXXXX * XXXXXXX# ///////////////////// XXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXX //////////////////// XXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XX ////////////// ////// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX * XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX * * @dev Nifty Gateway extension of customized NFT contract, encapsulates * logic for minting new tokens, and concluding the minting process. */ contract NiftyBuilderInstance is ERC721, ERC721Burnable { // Engine(s) of nifty type dynamism. address public _dateTimeContract00; address public _dateTimeContract01; /** * @dev Eroding and Reforming Bust of Zeus (Earth Day) * * @return uint256 index of asset */ function _bustOfZeus(IDateTime dateTime) internal view returns (uint256) { uint8 hour = dateTime.getHour(block.timestamp); uint8 threshold = 17; if (hour > threshold) { return uint256(3); } threshold = 11; if (hour > threshold) { return uint256(2); } threshold = 5; if (hour > threshold) { return uint256(1); } return uint256(0); } string[4] artifact01 = ["QmNWr9r6pEEnyh9aejue8upHSjYN24pWrAzpYmjRgseExr", //State 01 "QmZuaZ2RphWvnaxMxz9Pd95c4E5DPhE5BtSw4auztiMC1u", //State 02 "QmaB29NhdweR75hAWEehvcXCwXBwN8KBpny6uzdsUHNogv", //State 03 "QmfFCHSMAnjCqyPgTJDCQQuJJCpfqoupcihevgPxk7jHBF"];//State 04 /** * @dev Eroding and Reforming Venus of Arles (72.6 Years) * * @return uint256 index of asset */ function _venusOfArles(IDateTime dateTime) internal view returns (uint256) { uint16 offset = 2021; uint16 value = dateTime.getYear(block.timestamp) - offset; uint16 criterion = 73; uint16 result = value % criterion; return uint256(result); } string[73] artifact02 = ["QmR81UuQPkhfGE4K4cbbnBLj9Z5EZcEocu8YY18UM7NUM1", //State 01 "QmR4bA1ifjixhtkTYnz4VmHKWMpafZv4mFehmeGqcDQdvA", //State 02 "QmRzsgPoMsoYwiVKWYkFDeRjB3C2SiSKXVmTkDHGqy8SRq", //State 03 "QmRa4cdAHdnbfLX3s65rih6FYvwMfTePqSw46cDPR9gkX7", //State 04 "QmRMR9yLVFmLCGZyrSmuSPwh6KxkyScXVZ2akY3N4h7Hf5", //State 05 "QmRgrgEoac8hxMv4zJQmRhxVfUEAthxHQyV4vYUirXXo3W", //State 06 "QmcHYcrKNGs1NN8jnyJUnAzneK6DbaKtmLVwcZVp28Fuji", //State 07 "QmTjWk2p8eJcW6FR2y1t8mLcEAHs9QKt2tcPCcsXTXA5NA", //State 08 "QmNsf7GZUw2Bz4DSek2fcaXEvxSH6GdEUjmzUiprj9i2Ta", //State 09 "QmbEmMK7hLzCe9YWqhqXV3HQedEgorxtc642CkkCogVVho", //State 10 "QmbR2s2uPcywASUudpsujWmhxoFqy5hzxF9DM5ohRNQfWZ", //State 11 "QmWc3r6VknYB6vAu5astS8PzPjGwq3gQAexxt6g6H169gU", //State 12 "QmZrbFSuHf6zdM66RFgj2vCQatbAVYfyCBhHPsSzPzEz2M", //State 13 "QmeVyHYGP9QK3pSGpYPcMCrTrf8PWMppdq9cSxB8TjunRs", //State 14 "QmY9SvuK8rTSoZsAWxgaXS6fPeQSYhqsmWgqxAYbfuDM4y", //State 15 "QmawC7bUXhqwHeoAagd7UV2HhcGxpZ4PZHkU1rxM6ywgKV", //State 16 "QmSiysm4VWLJ19JF81U7enxcfjkb2mVyrzhJkZ6qCK42xS", //State 17 "QmYZHBoNxD9hAZASAThC93yRrGcfV5nCgi86wQNVgZkemV", //State 18 "QmRZ1B27Y1YuDoq6W32p8sFKUaj6hQwfaMJuCzWkA4wmKB", //State 19 "Qmb9b2QkBzSdkPooewAAQRcQULFYP49i8qdgRkZ7z5sijh", //State 20 "QmNNa8zqTZFpjo2ex2kd4x9vLZjK93WWmAp444VWS7NdVD", //State 21 "QmQaKQDstMwrEKZW5W2mbDywuNN6kxuE6MiB5UZZZ7umfJ", //State 22 "QmVcYsG9T3Ng5CJmVAQk7vHR5YzRaTfBkXFbYArqTsaEsA", //State 23 "Qma27xgagQLKhT89DDRvUTfmn5CacCXdn778bWQDUR6NG2", //State 24 "QmZbWLsVVRNgFyjjGWfkCAxisMEEGVJPrpbSiuYRS8unPc", //State 25 "QmNQ2aVkkaKV2eKQMPYVqCFBvaRsKtabAVg9LxCwibueBf", //State 26 "QmVMKPbTNU2fzDmwGTEPVxYsR8TF49yaVF8Vk1tT5uYGEY", //State 27 "QmaqrMBptBkdJcPyrKfrh8axTpD9a38qfodcoXsRNdnibp", //State 28 "QmYbvARyHSJqrp6PTeyvQj16EGrG7rLssoDfxr61JBVchX", //State 29 "QmSSrCyXCHeiKxxrr9V5gxZ4U4j3yt1mxvhGbrQKxRqiB8", //State 30 "QmWJov2kfhHPg7QLZkkbzC8WmKwD81wdATKE94hASfeiMM", //State 31 "Qmabw8dNheYekvDbCez1GDdC6tUdrgCLq8SgUsRFYcMRU8", //State 32 "QmWxi9VLRyMwXy11pSJbcG8XBgf25PXK3QbSZCc7V7aXoe", //State 33 "QmVGS6oXHtPh3jeYnqP7Y28Ti8a8UqJDwNbN6H7bPo9aMk", //State 34 "QmQ5tkbbYieCTvdVPL85PMZzij3MqB9TDsMiWh1UzR8CeN", //State 35 "QmbJkDacA74hcUQiATdSJfCkfxbKpj7CbZKJSfvGw7TZ3D", //State 36 "QmSAihqMxEqYPGaVf9ApFh416NF18soLcnpPM2iR77J7jB", //State 37 "QmZfwfjhjdRzQUBF98TSbZPUiWJod9GDiDWB7piK344b7a", //State 38 "QmUDn7VKVT5gAeNZ36kNA27f4cxS32SQSwsQujFFmebtJK", //State 39 "QmaR98jw8oiJyZRb39FcYuzf885GoXHGTK7uewvCN28FGG", //State 40 "QmTG9yZ4sTdWXPQNwYkRzdzHCjWDMk8qhBY8JCvZdvJksp", //State 41 "QmfRrs388cZqvGc5kctm5hrTNwhX6LeK4Eexk8adBxuYLj", //State 42 "QmdrxzuEecPEL6L7YVixucehiRY2aBWEbZAEeYQ8VkDNes", //State 43 "QmRrWxhqQfvgXV7nuGc58CQfXnE2QKq9WXYd2HaVQNxUJ9", //State 44 "QmXDPxvzeb1gpkchDY3qQai6RYBhALVWqo79HhPYDmbbiQ", //State 45 "QmYa3zGVn33SsGXD6pSXxARHvc9JHBDvRkPCeD8t9RadpH", //State 46 "QmfSkwPEQYbazMKwLrVaZmrFu7Rk6KVTqxVggr7F6zvwfF", //State 47 "QmaU1Hejt2kLTVpcnXfEpWcDT7MC8fb8uWjcBW5SCEgcBn", //State 48 "QmehTRiyb8MVxMJZccHnJk24QtuZdoXRoYc1qZJFWNM2DS", //State 49 "QmPzBPEMjaov2EdZF6mE5Sg4cki35MnnYGCp855MjBdQCS", //State 50 "QmXYgaCZFitc3PWMiNoNvesLPxq18Z2UXcGKQQrbmZsfCg", //State 51 "QmSqRdFM2rWX6igiBvfXbuMCbN9hx13DwrVTtQHi8GNvTE", //State 52 "QmWawbhnLFBC1J71QT55YC6htPwX6WDoLmwoj33aR75muC", //State 53 "QmYLiBGhwfuBWGNi3NmFQgVWj55b2Vxur2HvjVn7tMoD9Y", //State 54 "QmWW1YjGiVBjgSeaQqtNLyp1gKbyVdboqT7DUChXw3NgQt", //State 55 "QmecGhERiccBCXa7BHwASMZGVZRBQPBdnyDAuuzLctPRvB", //State 56 "QmPJNXZ1bXJU3FxCBgb4pUNHGBDQhuwVVYUUGWyuwp4vLX", //State 57 "QmPXsbSRwkWs5xAEqpt9hCbjNDmHsZvvJZkNH3b419FMDm", //State 58 "QmWaLpKgkQk2xrwyPp1kdmsB5xYcrAtiaT1U9tt7BfyxbU", //State 59 "QmU7LR8jiQcjAwTxxrXiGc3j7Ust7Ggjeb5Ysog4T5iW7N", //State 60 "QmcTxChkC259PTqzVgUtCaGstS6d5d3EtMcbnCX2bsZBNj", //State 61 "QmP8eGwqDLtmHD89Nofr54FsAcHvdL2mEMnCjssS9sEcwP", //State 62 "QmSVZPVDsZThK1spkL9Cy4SrxLTsNebXuRn2wCtAf3fXFm", //State 63 "QmUXfmP9k8SsUMNzC89y9F4NWRXkadBV5t6QBQkTTChRZP", //State 64 "QmXHLwFwwa5xiH3xXWPzvPLHRYoEQdKo9ZcMDs1dSfvERD", //State 65 "QmfTHh3E3JM5cZc3erTHJvkXeKh7i5SjAeXwBrQPwwTDTc", //State 66 "QmT6iHKZN9HvwWyS2d3XqBbhqPLXcBf1FXHHNNk7TcbAFu", //State 67 "QmfQpywZY2W2giE929VmqJ6m2NUwWKqeZT663yK661WB4L", //State 68 "QmRtiHoEE5kYrrnFjP51qTECMHBsdMH6PkJSt9uEEzkXXi", //State 69 "QmRiUTY6e8AtEdfvVSc3suRw7sEtRPdZeXkKwyVaM8bvcX", //State 70 "QmVQJD4g4jxJPi6XoCecXwWv7ULkWG5sU75UCFeM5XGPL5", //State 71 "QmZ2SjXuVdVGdR9viCpNhU8ZSRtsnEEErmjLq6LvMgDn4v", //State 72 "QmSx78hghW4cpWq3tinRYmKoHm665LEsDPPXmK1zmg8UpY"];//State 73 /** * @dev Eroding and Reforming Bust of Melpomene (Martian Day) * * @return uint256 index of asset */ function _bustOfMelpomene(IDateTime dateTime) internal view returns (uint256) { uint8 hour = dateTime.getHour(block.timestamp); uint8 weekday = dateTime.getWeekday(block.timestamp); uint8 criterion = 2; uint8 result = weekday - uint8(weekday / criterion); uint8 condition = 0; if (result == condition) { uint8 offset = 23; uint8 result = offset - hour; return uint256(result); } return uint256(hour); } string[24] artifact03 = ["Qma5iW6ch6kGE3GB1FkCvUt5LruJ3nZN7CjJQNZwifxSQH", //State 01 "QmNrSBLVJUNFHBqkT6r5utrNVELLGUPvnyYmXpFQMyw8Bs", //State 02 "QmZ1f4ku6MNt6XnoPTQReYva4AApL2JjBzydwfxPaRoEgk", //State 03 "QmZATZUY14RhFvqfGu8CX1ajUy4Qfx9KDNLYpJjAeiL2a3", //State 04 "QmRn6ncB9VVNNY8U6jpLawaQ5ogoRpKGon8XAcAXmHobeL", //State 05 "QmNLmKCa9EFRvYa8RbdiJjUjtmd6PF99VCaQLtkbfe5U42", //State 06 "Qmd4UgHyTFuSe3PTRJiUvmAqc3adSApzsoLFQeCbtidwpW", //State 07 "QmSxt7BUfePqABdwci7x9By3LgFUvbCM44WRsLoEFC3MYT", //State 08 "QmWetvFhJLuuJBSMhSPwt5xyCv3uW179FhF8MbmnbKUehW", //State 09 "QmXRShHWTLoKWVQZmbEQ1jDenwuV2BPHqNSYpNWnYoJ1K3", //State 10 "QmYkYqMX9FXY7MP5E9edr1ZeNEFBGqz1BNKCdcvkN7eFaN", //State 11 "QmYQqsn1FsMRm79hw8cXTkGPKH3pa3ouTGiTLveGJqm65A", //State 12 "QmYBNZ9AYGtGFQU4HUi2iAWCuhHt7nQ57dv7fuEeGfshTN", //State 13 "QmRsmx1ayeYaArsXRHVan1AQqqW8eBQKURguGfG5xjtpsN", //State 14 "QmZNtn3vk2SoJ4QJf6u2USnUvq5QNMrMqcTKC8s2fAghKY", //State 15 "QmYGN52qdpBoAJs5ye3RuyxgVfw1kAxv6Sjy4fRugb5eES", //State 16 "QmVuxM6foMHArx2qSmiuqhUWCVWid5r1Hhyq8w7aPHiecq", //State 17 "QmZe4njp7a3o9DyRbHFn1RDtGCiyXXoFHJZoxkmEjrFgwT", //State 18 "Qmeqk9eH3sTiucLTbpPAYq28Dj6icc9oAPJtiPej5e5ssC", //State 19 "QmekyAay43mjWax1byL5Erny5KyhN8pZgVhLE7Tg8waDR2", //State 20 "QmcjSYZuCHGS7zox5jyw5bE3NjHNghydjwkqiUMEj3hyPg", //State 21 "QmTigpNi4Y3iZQngxDUbKGcw2D7RrvACCiTVGxFmbRujKV", //State 22 "QmTJsYU9zaJR3pUQCLkLGYNan5N8a96sDoR3HgEwQz6Pzw", //State 23 "QmUH2WtFbawmshSo9PayGwnz4seZSS8NkGyGbuVYkod6Sh"];//State 24 // The artist associated with the collection. string private _creator; // Number of NFTs minted for a given 'typeCount'. mapping (uint256 => uint256) public _mintCount; /** * @dev Serves as a gas cost optimized boolean flag * to indicate whether the minting process has been * concluded for a given 'typeCount', correspinds * to the {_getFinalized} and {setFinalized}. */ mapping (uint256 => bytes32) private _finalized; /** * @dev Emitted when tokens are created. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); /** * @dev Ultimate instantiation of a Nifty Gateway NFT collection. */ constructor() ERC721() { _creator = "Daniel Arsham"; _dateTimeContract00 = 0x740a637ADD6492e5FaA907AF0fe708770B737058; _dateTimeContract01 = 0x740a637ADD6492e5FaA907AF0fe708770B737058; _setNiftyTypeName(1, "Eroding and Reforming Bust of Zeus (Earth Day)"); _setNiftyTypeName(2, "Eroding and Reforming Venus of Arles (72.6 Years)"); _setNiftyTypeName(3, "Eroding and Reforming Bust of Melpomene (Martian Day)"); } /** * Configurable address for DateTime. */ function setDateTimeContract00(address dateTimeContract_) onlyValidSender public { _dateTimeContract00 = dateTimeContract_; } /** * Configurable address for DateTime. */ function setDateTimeContract01(address dateTimeContract_) onlyValidSender public { _dateTimeContract01 = dateTimeContract_; } /** * @dev Generate canonical Nifty Gateway token representation. * Nifty contracts have a data model called a 'niftyType' (typeCount) * The 'niftyType' refers to a specific nifty in our contract, note * that it gives no information about the edition size. In a given * contract, 'niftyType' 1 could be an edition of 10, while 'niftyType' * 2 is a 1/1, etc. * The token IDs are encoded as follows: {id}{niftyType}{edition #} * 'niftyType' has 4 digits, and edition number does as well, to allow * for 9999 possible 'niftyType' and 9999 of each edition in each contract. * Example token id: [500010270] * This is from contract #5, it is 'niftyType' 1 in the contract, and it is * edition #270 of 'niftyType' 1. */ function _encodeTokenId(uint256 niftyType, uint256 tokenNumber) private view returns (uint256) { return (topLevelMultiplier + (niftyType * midLevelMultiplier) + tokenNumber); } /** * @dev Determine whether it is possible to mint additional NFTs for this 'niftyType'. */ function _getFinalized(uint256 niftyType) public view returns (bool) { bytes32 chunk = _finalized[niftyType / 256]; return (chunk & bytes32(1 << (niftyType % 256))) != 0x0; } /** * @dev Prevent the minting of additional NFTs of this 'niftyType'. */ function setFinalized(uint256 niftyType) public onlyValidSender { uint256 quotient = niftyType / 256; bytes32 chunk = _finalized[quotient]; _finalized[quotient] = chunk | bytes32(1 << (niftyType % 256)); } /** * @dev The artist of this collection. */ function creator() public view virtual returns (string memory) { return _creator; } /** * @dev Assign the root location where the artifact assets are stored. */ function setBaseURI(string memory baseURI) public onlyValidSender { _setBaseURI(baseURI); } /** * @dev Allow owner to change nifty name, by 'niftyType'. */ function setNiftyName(uint256 niftyType, string memory niftyName) public onlyValidSender { _setNiftyTypeName(niftyType, niftyName); } /** * @dev Assign the IPFS hash of canonical artifcat file, by 'niftyType'. */ function setNiftyIPFSHash(uint256 niftyType, string memory hashIPFS) public onlyValidSender { _setTokenIPFSHashNiftyType(niftyType, hashIPFS); } /** * @dev Create specified number of nifties en masse. * Once an NFT collection is spawned by the factory contract, we make calls to set the IPFS * hash (above) for each Nifty type in the collection. * Subsequently calls are issued to this function to mint the appropriate number of tokens * for the project. */ function mintNifty(uint256 niftyType, uint256 count) public onlyValidSender { require(!_getFinalized(niftyType), "NiftyBuilderInstance: minting concluded for nifty type"); uint256 tokenNumber = _mintCount[niftyType] + 1; uint256 tokenId00 = _encodeTokenId(niftyType, tokenNumber); uint256 tokenId01 = tokenId00 + count - 1; for (uint256 tokenId = tokenId00; tokenId <= tokenId01; tokenId++) { _owners[tokenId] = _defaultOwner; } _mintCount[niftyType] += count; _balances[_defaultOwner] += count; emit ConsecutiveTransfer(tokenId00, tokenId01, address(0), _defaultOwner); } /** * @dev Returns an IPFS hash for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query. * @return IPFS hash for this (_typeCount) NFT. */ function tokenIPFSHash(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: IPFS hash query for nonexistent token"); IDateTime dateTime00 = IDateTime(_dateTimeContract00); uint256 niftyType = _getNiftyTypeId(tokenId); if (niftyType == 2) { uint256 value = _venusOfArles(dateTime00); return artifact02[value]; } else if (niftyType == 1) { uint256 value = _bustOfZeus(dateTime00); return artifact01[value]; } IDateTime dateTime01 = IDateTime(_dateTimeContract01); uint256 value = _bustOfMelpomene(dateTime01); return artifact03[value]; } }
* @dev Ultimate instantiation of a Nifty Gateway NFT collection./
constructor() ERC721() { _creator = "Daniel Arsham"; _dateTimeContract00 = 0x740a637ADD6492e5FaA907AF0fe708770B737058; _dateTimeContract01 = 0x740a637ADD6492e5FaA907AF0fe708770B737058; _setNiftyTypeName(1, "Eroding and Reforming Bust of Zeus (Earth Day)"); _setNiftyTypeName(2, "Eroding and Reforming Venus of Arles (72.6 Years)"); _setNiftyTypeName(3, "Eroding and Reforming Bust of Melpomene (Martian Day)"); }
4,807,849
[ 1, 57, 5618, 4988, 28380, 434, 279, 423, 2136, 93, 11381, 423, 4464, 1849, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 27, 5340, 1435, 288, 203, 3639, 389, 20394, 273, 315, 40, 28662, 292, 1201, 674, 301, 14432, 203, 3639, 389, 712, 950, 8924, 713, 273, 374, 92, 5608, 20, 69, 4449, 27, 8355, 1105, 9975, 73, 25, 29634, 37, 29, 8642, 6799, 20, 3030, 27, 6840, 4700, 20, 38, 27, 6418, 6260, 28, 31, 203, 3639, 389, 712, 950, 8924, 1611, 273, 374, 92, 5608, 20, 69, 4449, 27, 8355, 1105, 9975, 73, 25, 29634, 37, 29, 8642, 6799, 20, 3030, 27, 6840, 4700, 20, 38, 27, 6418, 6260, 28, 31, 203, 3639, 389, 542, 50, 2136, 93, 7947, 12, 21, 16, 315, 41, 303, 7459, 471, 868, 687, 310, 605, 641, 434, 2285, 10315, 261, 41, 27076, 13735, 2225, 1769, 203, 3639, 389, 542, 50, 2136, 93, 7947, 12, 22, 16, 315, 41, 303, 7459, 471, 868, 687, 310, 776, 11797, 434, 1201, 1040, 261, 9060, 18, 26, 16666, 87, 2225, 1769, 203, 3639, 389, 542, 50, 2136, 93, 7947, 12, 23, 16, 315, 41, 303, 7459, 471, 868, 687, 310, 605, 641, 434, 490, 1992, 362, 4009, 261, 49, 485, 2779, 13735, 2225, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.4; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @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 `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, 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); } 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 your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { 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]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { 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; uint256 public totalSupply; } //name this contract whatever you'd like contract MapleCoin is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* 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 = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function MapleCoin( ) { balances[msg.sender] = 10000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 10000000000; // Update total supply (100000 for example) name = "MAPLE COIN"; // Set the name for display purposes decimals = 6; // Amount of decimals for display purposes symbol = "MPL"; // 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)) { throw; } return true; } }
Set the name for display purposes
name = "MAPLE COIN";
1,218,072
[ 1, 694, 326, 508, 364, 2562, 13694, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 508, 273, 315, 8352, 900, 385, 6266, 14432, 4766, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: lib/ReentrancyGuard.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.12; /** * @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 () public { _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: iface/IPriceController.sol pragma solidity ^0.6.12; interface IPriceController { function getPriceForPToken(address token, address uToken, address payback) external payable returns (uint256 tokenPrice, uint256 pTokenPrice); } // File: iface/IInsurancePool.sol pragma solidity ^0.6.12; interface IInsurancePool { function setPTokenToIns(address pToken, address ins) external; function destroyPToken(address pToken, uint256 amount, address token) external; function eliminate(address pToken, address token) external; function setLatestTime(address token) external; } // File: iface/IERC20.sol pragma solidity ^0.6.12; interface IERC20 { function decimals() external view returns (uint8); function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: lib/Address.sol pragma solidity 0.6.12; library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; 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"); (bool success, ) = recipient.call{value:amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: lib/SafeERC20.sol pragma solidity 0.6.12; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { 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(ERC20 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(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(ERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface ERC20 { 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); } // File: lib/TransferHelper.sol pragma solidity ^0.6.12; // 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'); } } // File: iface/IPTokenFactory.sol pragma solidity ^0.6.12; interface IPTokenFactory { function getGovernance() external view returns(address); function getPTokenOperator(address contractAddress) external view returns(bool); function getPTokenAuthenticity(address pToken) external view returns(bool); } // File: iface/IParasset.sol pragma solidity ^0.6.12; interface IParasset { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function destroy(uint256 amount, address account) external; function issuance(uint256 amount, address account) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: lib/SafeMath.sol pragma solidity ^0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } function div(uint x, uint y) internal pure returns (uint z) { require(y > 0, "ds-math-div-zero"); z = x / y; // assert(a == b * c + a % b); // There is no case in which this doesn't hold } } // File: PToken.sol pragma solidity ^0.6.12; contract PToken is IParasset { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 public _totalSupply = 0; string public name = ""; string public symbol = ""; uint8 public decimals = 18; IPTokenFactory pTokenFactory; constructor (string memory _name, string memory _symbol) public { name = _name; symbol = _symbol; pTokenFactory = IPTokenFactory(address(msg.sender)); } //---------modifier--------- modifier onlyGovernance() { require(address(msg.sender) == pTokenFactory.getGovernance(), "Log:PToken:!governance"); _; } modifier onlyPool() { require(pTokenFactory.getPTokenOperator(address(msg.sender)), "Log:PToken:!Pool"); _; } //---------view--------- // Query factory contract address function getPTokenFactory() public view returns(address) { return address(pTokenFactory); } /// @notice The view of totalSupply /// @return The total supply of ntoken function totalSupply() override public view returns (uint256) { return _totalSupply; } /// @dev The view of balances /// @param owner The address of an account /// @return The balance of the account function balanceOf(address owner) override public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) override public view returns (uint256) { return _allowed[owner][spender]; } //---------transaction--------- function changeFactory(address factory) public onlyGovernance { pTokenFactory = IPTokenFactory(address(factory)); } function rename(string memory _name, string memory _symbol) public onlyGovernance { name = _name; symbol = _symbol; } function transfer(address to, uint256 value) override public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) override public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) override public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _transfer(address from, address to, uint256 value) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function destroy(uint256 amount, address account) override external onlyPool{ require(_balances[account] >= amount, "Log:PToken:!destroy"); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0x0), amount); } function issuance(uint256 amount, address account) override external onlyPool{ _balances[account] = _balances[account].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0x0), account, amount); } } // File: MortgagePool.sol pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; contract MortgagePool is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; // Governance address address public governance; // Underlying asset address => PToken address mapping(address=>address) public underlyingToPToken; // PToken address => Underlying asset address mapping(address=>address) public pTokenToUnderlying; // PToken address => Mortgage asset address => Bool mapping(address=>mapping(address=>bool)) mortgageAllow; // PToken address => Mortgage asset address => User address => Debt data mapping(address=>mapping(address=>mapping(address=>PersonalLedger))) ledger; // PToken address => Mortgage asset address => Users who have created debt positions(address) mapping(address=>mapping(address=>address[])) ledgerArray; // Mortgage asset address => Maximum mortgage rate mapping(address=>uint256) maxRate; // Mortgage asset address => Liquidation line mapping(address=>uint256) liquidationLine; // PriceController contract IPriceController quary; // Insurance pool contract IInsurancePool insurancePool; // PToken creation factory contract IPTokenFactory pTokenFactory; // Market base interest rate uint256 r0 = 0.025 ether; // Amount of blocks produced in a year uint256 oneYear = 2400000; // Status uint8 public flag; // = 0: pause // = 1: active // = 2: out only struct PersonalLedger { uint256 mortgageAssets; // Amount of mortgaged assets uint256 parassetAssets; // Amount of debt(Ptoken,Stability fee not included) uint256 blockHeight; // The block height of the last operation uint256 rate; // Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) bool created; // Is it created } event FeeValue(address pToken, uint256 value); /// @dev Initialization method /// @param factoryAddress PToken creation factory contract constructor (address factoryAddress) public { pTokenFactory = IPTokenFactory(factoryAddress); governance = pTokenFactory.getGovernance(); flag = 0; } //---------modifier--------- modifier onlyGovernance() { require(msg.sender == governance, "Log:MortgagePool:!gov"); _; } modifier whenActive() { require(flag == 1, "Log:MortgagePool:!active"); _; } modifier outOnly() { require(flag != 0, "Log:MortgagePool:!0"); _; } //---------view--------- /// @dev Calculate the stability fee /// @param parassetAssets Amount of debt(Ptoken,Stability fee not included) /// @param blockHeight The block height of the last operation /// @param rate Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) /// @param nowRate Current mortgage rate (not including stability fee) /// @return fee function getFee(uint256 parassetAssets, uint256 blockHeight, uint256 rate, uint256 nowRate) public view returns(uint256) { uint256 topOne = parassetAssets.mul(r0).mul(block.number.sub(blockHeight)); uint256 ratePlus = rate.add(nowRate); uint256 topTwo = parassetAssets.mul(r0).mul(block.number.sub(blockHeight)).mul(uint256(3).mul(ratePlus)); uint256 bottom = oneYear.mul(1 ether); return topOne.div(bottom).add(topTwo.div(bottom.mul(1 ether).mul(2))); } /// @dev Calculate the mortgage rate /// @param mortgageAssets Amount of mortgaged assets /// @param parassetAssets Amount of debt /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param pTokenPrice PToken price(1 ETH = ? pToken) /// @return mortgage rate function getMortgageRate(uint256 mortgageAssets, uint256 parassetAssets, uint256 tokenPrice, uint256 pTokenPrice) public pure returns(uint256) { if (mortgageAssets == 0 || pTokenPrice == 0) { return 0; } return parassetAssets.mul(tokenPrice).mul(1 ether).div(pTokenPrice.mul(mortgageAssets)); } /// @dev Get real-time data of the current debt warehouse /// @param mortgageToken Mortgage asset address /// @param pToken PToken address /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param uTokenPrice Underlying asset price(1 ETH = ? Underlying asset) /// @param maxRateNum Maximum mortgage rate /// @param owner Debt owner /// @return fee Stability fee /// @return mortgageRate Real-time mortgage rate(Including stability fee) /// @return maxSubM The maximum amount of mortgage assets can be reduced /// @return maxAddP Maximum number of coins that can be added function getInfoRealTime(address mortgageToken, address pToken, uint256 tokenPrice, uint256 uTokenPrice, uint256 maxRateNum, uint256 owner) public view returns(uint256 fee, uint256 mortgageRate, uint256 maxSubM, uint256 maxAddP) { PersonalLedger memory pLedger = ledger[pToken][mortgageToken][address(owner)]; if (pLedger.mortgageAssets == 0 && pLedger.parassetAssets == 0) { return (0,0,0,0); } uint256 pTokenPrice = getDecimalConversion(pTokenToUnderlying[pToken], uTokenPrice, pToken); uint256 tokenPriceAmount = tokenPrice; fee = getFee(pLedger.parassetAssets, pLedger.blockHeight, pLedger.rate, getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets, tokenPriceAmount, pTokenPrice)); mortgageRate = getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets.add(fee), tokenPriceAmount, pTokenPrice); uint256 maxRateEther = maxRateNum.mul(0.01 ether); if (mortgageRate >= maxRateEther) { maxSubM = 0; maxAddP = 0; } else { maxSubM = pLedger.mortgageAssets.sub(pLedger.parassetAssets.mul(tokenPriceAmount).mul(1 ether).div(maxRateEther.mul(pTokenPrice))); maxAddP = pLedger.mortgageAssets.mul(pTokenPrice).mul(maxRateEther).div(uint256(1 ether).mul(tokenPriceAmount)).sub(pLedger.parassetAssets); } } /// @dev Uniform accuracy /// @param inputToken Initial token /// @param inputTokenAmount Amount of token /// @param outputToken Converted token /// @return stability Amount of outputToken function getDecimalConversion(address inputToken, uint256 inputTokenAmount, address outputToken) public view returns(uint256) { uint256 inputTokenDec = 18; uint256 outputTokenDec = 18; if (inputToken != address(0x0)) { inputTokenDec = IERC20(inputToken).decimals(); } if (outputToken != address(0x0)) { outputTokenDec = IERC20(outputToken).decimals(); } return inputTokenAmount.mul(10**outputTokenDec).div(10**inputTokenDec); } /// @dev View debt warehouse data /// @param pToken pToken address /// @param mortgageToken mortgage asset address /// @param owner debt owner /// @return mortgageAssets amount of mortgaged assets /// @return parassetAssets amount of debt(Ptoken,Stability fee not included) /// @return blockHeight the block height of the last operation /// @return rate Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) /// @return created is it created function getLedger(address pToken, address mortgageToken, address owner) public view returns(uint256 mortgageAssets, uint256 parassetAssets, uint256 blockHeight, uint256 rate, bool created) { PersonalLedger memory pLedger = ledger[pToken][mortgageToken][address(owner)]; return (pLedger.mortgageAssets, pLedger.parassetAssets, pLedger.blockHeight, pLedger.rate, pLedger.created); } /// @dev View governance address /// @return governance address function getGovernance() external view returns(address) { return governance; } /// @dev View insurance pool address /// @return insurance pool address function getInsurancePool() external view returns(address) { return address(insurancePool); } /// @dev View the market base interest rate /// @return market base interest rate function getR0() external view returns(uint256) { return r0; } /// @dev View the amount of blocks produced in a year /// @return amount of blocks produced in a year function getOneYear() external view returns(uint256) { return oneYear; } /// @dev View the maximum mortgage rate /// @param mortgageToken Mortgage asset address /// @return maximum mortgage rate function getMaxRate(address mortgageToken) external view returns(uint256) { return maxRate[mortgageToken]; } /// @dev View the liquidation line /// @param mortgageToken Mortgage asset address /// @return liquidation line function getLiquidationLine(address mortgageToken) external view returns(uint256) { return liquidationLine[mortgageToken]; } /// @dev View the priceController contract address /// @return priceController contract address function getPriceController() external view returns(address) { return address(quary); } /// @dev View the ptoken address according to the underlying asset /// @param uToken Underlying asset address /// @return ptoken address function getUnderlyingToPToken(address uToken) external view returns(address) { return underlyingToPToken[uToken]; } /// @dev View the underlying asset according to the ptoken address /// @param pToken ptoken address /// @return underlying asset function getPTokenToUnderlying(address pToken) external view returns(address) { return pTokenToUnderlying[pToken]; } /// @dev View the debt array length /// @param pToken ptoken address /// @param mortgageToken mortgage asset address /// @return debt array length function getLedgerArrayNum(address pToken, address mortgageToken) external view returns(uint256) { return ledgerArray[pToken][mortgageToken].length; } /// @dev View the debt owner /// @param pToken ptoken address /// @param mortgageToken mortgage asset address /// @param index array subscript /// @return debt owner function getLedgerAddress(address pToken, address mortgageToken, uint256 index) external view returns(address) { return ledgerArray[pToken][mortgageToken][index]; } //---------governance---------- /// @dev Set contract status /// @param num 0: pause, 1: active, 2: out only function setFlag(uint8 num) public onlyGovernance { flag = num; } /// @dev Allow asset mortgage to generate ptoken /// @param pToken ptoken address /// @param mortgageToken mortgage asset address /// @param allow allow mortgage function setMortgageAllow(address pToken, address mortgageToken, bool allow) public onlyGovernance { mortgageAllow[pToken][mortgageToken] = allow; } /// @dev Set insurance pool contract /// @param add insurance pool contract function setInsurancePool(address add) public onlyGovernance { insurancePool = IInsurancePool(add); } /// @dev Set market base interest rate /// @param num market base interest rate(num = ? * 1 ether) function setR0(uint256 num) public onlyGovernance { r0 = num; } /// @dev Set the amount of blocks produced in a year /// @param num amount of blocks produced in a year function setOneYear(uint256 num) public onlyGovernance { oneYear = num; } /// @dev Set liquidation line /// @param mortgageToken mortgage asset address /// @param num liquidation line(num = ? * 100) function setLiquidationLine(address mortgageToken, uint256 num) public onlyGovernance { liquidationLine[mortgageToken] = num.mul(0.01 ether); } /// @dev Set the maximum mortgage rate /// @param mortgageToken mortgage asset address /// @param num maximum mortgage rate(num = ? * 100) function setMaxRate(address mortgageToken, uint256 num) public onlyGovernance { maxRate[mortgageToken] = num.mul(0.01 ether); } /// @dev Set priceController contract address /// @param add priceController contract address function setPriceController(address add) public onlyGovernance { quary = IPriceController(add); } /// @dev Set the underlying asset and ptoken mapping and /// Set the latest redemption time of ptoken insurance /// @param uToken underlying asset address /// @param pToken ptoken address function setInfo(address uToken, address pToken) public onlyGovernance { require(underlyingToPToken[uToken] == address(0x0), "Log:MortgagePool:underlyingToPToken"); require(address(insurancePool) != address(0x0), "Log:MortgagePool:0x0"); underlyingToPToken[uToken] = address(pToken); pTokenToUnderlying[address(pToken)] = uToken; insurancePool.setLatestTime(uToken); } //---------transaction--------- /// @dev Set governance address function setGovernance() public { governance = pTokenFactory.getGovernance(); require(governance != address(0x0), "Log:MortgagePool:0x0"); } /// @dev Mortgage asset casting ptoken /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of mortgaged assets /// @param rate custom mortgage rate function coin(address mortgageToken, address pToken, uint256 amount, uint256 rate) public payable whenActive nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); require(rate > 0 && rate <= maxRate[mortgageToken], "Log:MortgagePool:rate!=0"); require(amount > 0, "Log:MortgagePool:amount!=0"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; // Get the price and transfer to the mortgage token uint256 tokenPrice; uint256 pTokenPrice; if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransferFrom(address(msg.sender), address(this), amount); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); } else { require(msg.value >= amount, "Log:MortgagePool:!msg.value"); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], uint256(msg.value).sub(amount)); } // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Additional ptoken issuance uint256 pTokenAmount = amount.mul(pTokenPrice).mul(rate).div(tokenPrice.mul(100)); PToken(pToken).issuance(pTokenAmount, address(msg.sender)); // Update debt information pLedger.mortgageAssets = mortgageAssets.add(amount); pLedger.parassetAssets = parassetAssets.add(pTokenAmount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // Tag created if (pLedger.created == false) { ledgerArray[pToken][mortgageToken].push(address(msg.sender)); pLedger.created = true; } } /// @dev Increase mortgage assets /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of mortgaged assets function supplement(address mortgageToken, address pToken, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); require(amount > 0, "Log:MortgagePool:!amount"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(pLedger.created, "Log:MortgagePool:!created"); // Get the price and transfer to the mortgage token uint256 tokenPrice; uint256 pTokenPrice; if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransferFrom(address(msg.sender), address(this), amount); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); } else { require(msg.value >= amount, "Log:MortgagePool:!msg.value"); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], uint256(msg.value).sub(amount)); } // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Update debt information pLedger.mortgageAssets = mortgageAssets.add(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); } /// @dev Reduce mortgage assets /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of mortgaged assets function decrease(address mortgageToken, address pToken, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= mortgageAssets, "Log:MortgagePool:!amount"); require(pLedger.created, "Log:MortgagePool:!created"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Update debt information pLedger.mortgageAssets = mortgageAssets.sub(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); // The debt warehouse mortgage rate cannot be greater than the maximum mortgage rate require(pLedger.rate <= maxRate[mortgageToken], "Log:MortgagePool:!maxRate"); // Transfer out mortgage assets if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransfer(address(msg.sender), amount); } else { TransferHelper.safeTransferETH(address(msg.sender), amount); } } /// @dev Increase debt (increase coinage) /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of debt function increaseCoinage(address mortgageToken, address pToken, uint256 amount) public payable whenActive nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); require(amount > 0, "Log:MortgagePool:!amount"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(pLedger.created, "Log:MortgagePool:!created"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Update debt information pLedger.parassetAssets = parassetAssets.add(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // The debt warehouse mortgage rate cannot be greater than the maximum mortgage rate require(pLedger.rate <= maxRate[mortgageToken], "Log:MortgagePool:!maxRate"); // Additional ptoken issuance PToken(pToken).issuance(amount, address(msg.sender)); } /// @dev Reduce debt (increase coinage) /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of debt function reducedCoinage(address mortgageToken, address pToken, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; address uToken = pTokenToUnderlying[pToken]; require(amount > 0 && amount <= parassetAssets, "Log:MortgagePool:!amount"); require(pLedger.created, "Log:MortgagePool:!created"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, uToken, msg.value); // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), amount.add(fee)); // Eliminate negative accounts insurancePool.eliminate(pToken, uToken); emit FeeValue(pToken, fee); } // Update debt information pLedger.parassetAssets = parassetAssets.sub(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // Destroy ptoken insurancePool.destroyPToken(pToken, amount, uToken); } /// @dev Liquidation of debt /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param account debt owner address /// @param amount amount of mortgaged assets function liquidation(address mortgageToken, address pToken, address account, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][account]; require(pLedger.created, "Log:MortgagePool:!created"); uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= mortgageAssets, "Log:MortgagePool:!amount"); // Get the price address uToken = pTokenToUnderlying[pToken]; (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, uToken, msg.value); // Judging the liquidation line checkLine(pLedger, tokenPrice, pTokenPrice, mortgageToken); // Calculate the amount of ptoken uint256 pTokenAmount = amount.mul(pTokenPrice).mul(90).div(tokenPrice.mul(100)); // Transfer to ptoken ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), pTokenAmount); // Eliminate negative accounts insurancePool.eliminate(pToken, uToken); // Calculate the debt for destruction uint256 offset = parassetAssets.mul(amount).div(mortgageAssets); // Destroy ptoken insurancePool.destroyPToken(pToken, offset, uToken); // Update debt information pLedger.mortgageAssets = mortgageAssets.sub(amount); pLedger.parassetAssets = parassetAssets.sub(offset); // MortgageAssets liquidation, mortgage rate and block number are not updated if (pLedger.mortgageAssets == 0) { pLedger.parassetAssets = 0; pLedger.blockHeight = 0; pLedger.rate = 0; } // Transfer out mortgage asset if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransfer(address(msg.sender), amount); } else { TransferHelper.safeTransferETH(address(msg.sender), amount); } } /// @dev Check the liquidation line /// @param pLedger debt warehouse ledger /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param pTokenPrice PToken price(1 ETH = ? pToken) /// @param mortgageToken mortgage asset address function checkLine(PersonalLedger memory pLedger, uint256 tokenPrice, uint256 pTokenPrice, address mortgageToken) private view { uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; // The current mortgage rate cannot exceed the liquidation line uint256 mortgageRate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); uint256 fee = 0; if (parassetAssets > 0 && block.number > pLedger.blockHeight && pLedger.blockHeight != 0) { fee = getFee(parassetAssets, pLedger.blockHeight, pLedger.rate, mortgageRate); } require(getMortgageRate(mortgageAssets, parassetAssets.add(fee), tokenPrice, pTokenPrice) > liquidationLine[mortgageToken], "Log:MortgagePool:!liquidationLine"); } /// @dev Get price /// @param mortgageToken mortgage asset address /// @param uToken underlying asset address /// @param priceValue price fee /// @return tokenPrice Mortgage asset price(1 ETH = ? token) /// @return pTokenPrice PToken price(1 ETH = ? pToken) function getPriceForPToken(address mortgageToken, address uToken, uint256 priceValue) private returns (uint256 tokenPrice, uint256 pTokenPrice) { (tokenPrice, pTokenPrice) = quary.getPriceForPToken{value:priceValue}(mortgageToken, uToken, msg.sender); } // function takeOutERC20(address token, uint256 amount, address to) public onlyGovernance { // ERC20(token).safeTransfer(address(to), amount); // } // function takeOutETH(uint256 amount, address to) public onlyGovernance { // TransferHelper.safeTransferETH(address(to), amount); // } }
@dev Liquidation of debt @param mortgageToken mortgage asset address @param pToken ptoken address @param account debt owner address @param amount amount of mortgaged assets Get the price Judging the liquidation line Calculate the amount of ptoken Transfer to ptoken Eliminate negative accounts Calculate the debt for destruction Destroy ptoken Update debt information MortgageAssets liquidation, mortgage rate and block number are not updated Transfer out mortgage asset
function liquidation(address mortgageToken, address pToken, address account, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][account]; require(pLedger.created, "Log:MortgagePool:!created"); uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= mortgageAssets, "Log:MortgagePool:!amount"); address uToken = pTokenToUnderlying[pToken]; (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, uToken, msg.value); checkLine(pLedger, tokenPrice, pTokenPrice, mortgageToken); uint256 pTokenAmount = amount.mul(pTokenPrice).mul(90).div(tokenPrice.mul(100)); ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), pTokenAmount); insurancePool.eliminate(pToken, uToken); uint256 offset = parassetAssets.mul(amount).div(mortgageAssets); insurancePool.destroyPToken(pToken, offset, uToken); pLedger.mortgageAssets = mortgageAssets.sub(amount); pLedger.parassetAssets = parassetAssets.sub(offset); if (pLedger.mortgageAssets == 0) { pLedger.parassetAssets = 0; pLedger.blockHeight = 0; pLedger.rate = 0; } if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransfer(address(msg.sender), amount); TransferHelper.safeTransferETH(address(msg.sender), amount); } }
14,806,370
[ 1, 48, 18988, 350, 367, 434, 18202, 88, 225, 312, 499, 75, 410, 1345, 312, 499, 75, 410, 3310, 1758, 225, 293, 1345, 293, 2316, 1758, 225, 2236, 18202, 88, 3410, 1758, 225, 3844, 3844, 434, 312, 499, 75, 11349, 7176, 968, 326, 6205, 804, 1100, 1998, 326, 4501, 26595, 367, 980, 9029, 326, 3844, 434, 293, 2316, 12279, 358, 293, 2316, 512, 7091, 3322, 6092, 9484, 9029, 326, 18202, 88, 364, 2832, 313, 4062, 15701, 293, 2316, 2315, 18202, 88, 1779, 490, 499, 75, 410, 10726, 4501, 26595, 367, 16, 312, 499, 75, 410, 4993, 471, 1203, 1300, 854, 486, 3526, 12279, 596, 312, 499, 75, 410, 3310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4501, 26595, 367, 12, 2867, 312, 499, 75, 410, 1345, 16, 7010, 7682, 1758, 293, 1345, 16, 203, 7682, 1758, 2236, 16, 203, 7682, 2254, 5034, 3844, 13, 1071, 8843, 429, 596, 3386, 1661, 426, 8230, 970, 288, 203, 203, 377, 202, 6528, 12, 81, 499, 75, 410, 7009, 63, 84, 1345, 6362, 81, 499, 75, 410, 1345, 6487, 315, 1343, 30, 49, 499, 75, 410, 2864, 30, 5, 81, 499, 75, 410, 7009, 8863, 203, 377, 202, 8346, 287, 28731, 2502, 293, 28731, 273, 16160, 63, 84, 1345, 6362, 81, 499, 75, 410, 1345, 6362, 4631, 15533, 203, 3639, 2583, 12, 84, 28731, 18, 4824, 16, 315, 1343, 30, 49, 499, 75, 410, 2864, 30, 5, 4824, 8863, 203, 3639, 2254, 5034, 779, 9406, 10726, 273, 293, 28731, 18, 1065, 9406, 10726, 31, 203, 3639, 2254, 5034, 312, 499, 75, 410, 10726, 273, 293, 28731, 18, 81, 499, 75, 410, 10726, 31, 203, 3639, 2583, 12, 8949, 405, 374, 597, 3844, 1648, 312, 499, 75, 410, 10726, 16, 315, 1343, 30, 49, 499, 75, 410, 2864, 30, 5, 8949, 8863, 203, 203, 3639, 1758, 582, 1345, 273, 293, 1345, 774, 14655, 6291, 63, 84, 1345, 15533, 203, 377, 202, 12, 11890, 5034, 1147, 5147, 16, 2254, 5034, 293, 1345, 5147, 13, 273, 25930, 1290, 52, 1345, 12, 81, 499, 75, 410, 1345, 16, 582, 1345, 16, 1234, 18, 1132, 1769, 203, 540, 203, 3639, 866, 1670, 12, 84, 28731, 16, 1147, 5147, 16, 293, 1345, 5147, 16, 312, 499, 75, 410, 2 ]
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/governance/utils/Votes.sol
* @dev The clock was incorrectly modified./* @dev Lookup to future votes is not available./* @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting), in which case {CLOCK_MODE} should be overridden as well to match./
function clock() public view virtual returns (uint48) { return Time.blockNumber(); }
8,083,898
[ 1, 1986, 7268, 1703, 25621, 4358, 18, 19, 225, 8834, 358, 3563, 19588, 353, 486, 2319, 18, 19, 225, 18051, 1399, 364, 2982, 1998, 26402, 18, 4480, 506, 11000, 358, 2348, 2858, 2511, 26402, 261, 464, 331, 17128, 3631, 316, 1492, 648, 288, 39, 6589, 67, 7038, 97, 1410, 506, 11000, 487, 5492, 358, 845, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7268, 1435, 1071, 1476, 5024, 1135, 261, 11890, 8875, 13, 288, 203, 3639, 327, 2647, 18, 2629, 1854, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => bool) private authorizedCallers; //airline struct with name, whether they funded, the amt of fundes, # of votes received if registered after previous 4 struct Airline { bool isRegistered; string airlineName; bool isFunded; uint256 funds; uint256 numberOfVotesReceived; mapping (address => bool) otherAirlineVotes; } uint256 private numberOfAirlinesRegistered = 0; uint256 private numberOfAirlinesFunded = 0; // flight struct struct Flight { address airline; string flightName; uint256 flightDateTime; uint8 statusCode; uint256 updatedTimestamp; address[] insuredPassengers; } // string mapping to flight mapping(bytes32 => Flight) private flights; bytes32[] private currentFlights; mapping(address => Airline) private airlines; // passenger with multiply flights struct Passenger { mapping(bytes32 => uint256) insuranceAmountForFlight; mapping(bytes32 => bool) passengerOnFlight; uint256 balance; } mapping(address => Passenger) passengers; // the contract holds balance of insurance uint256 private contractBalance = 0 ether; // so we don't go in the hole uint256 private insuranceBalance = 0 ether; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AuthorizedContract(address _contractId); event OperationalStatusChanged(bool _state); constructor(address airline) public payable { contractOwner = msg.sender; contractBalance = contractBalance.add(msg.value); //register the initial airline (United) _registerAirline(airline, 'United', msg.sender, true, false); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireIsCallerAuthorized() { require(authorizedCallers[msg.sender] || (msg.sender == contractOwner), "Caller is not authorised"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function getContractOwner() public view returns (address) { return contractOwner; } function isOperational() public view returns(bool) { return operational; } function isFlightRegistered(bytes32 key) external view returns(bool) { return flights[key].airline != address(0); } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; emit OperationalStatusChanged(mode); } function authorizeCaller(address contractAddress) external requireContractOwner { require(authorizedCallers[contractAddress] == false, "Address has already be registered"); authorizedCallers[contractAddress] = true; emit AuthorizedContract(contractAddress); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function hasAirlineAlreadyVoted(address _address, address _registeredAirline) external view requireIsOperational requireIsCallerAuthorized returns(bool) { return airlines[_address].otherAirlineVotes[_registeredAirline]; } function isAirline( address _address) external view returns(bool) { return airlines[_address].isRegistered; } //public function function registerAirline(address _address, string _airlineName, address _registeredAirline, bool _isRegistered, bool _isFunded) external requireIsOperational requireIsCallerAuthorized { _registerAirline(_address, _airlineName, _registeredAirline, _isRegistered, _isFunded); } //private function so can be called from constructor function _registerAirline(address _address, string _airlineName, address _registeredAirline, bool _isRegistered, bool _isFunded) private { airlines[_address].otherAirlineVotes[_registeredAirline] = true; airlines[_address].airlineName = _airlineName; airlines[_address].isRegistered = _isRegistered; if(airlines[_address].isRegistered) { numberOfAirlinesRegistered = numberOfAirlinesRegistered.add(1); } airlines[_address].numberOfVotesReceived = airlines[_address].numberOfVotesReceived.add(1); } function isAirlineRegistered(address _airline) public view requireIsOperational returns (bool success) { return airlines[_airline].isRegistered; } function getNumberOfAirlinesRegistered() external view requireIsOperational returns(uint256 _count) { return numberOfAirlinesRegistered; } function getNumberOfAirlineVotes(address _address) external view requireIsOperational returns(uint256) { return airlines[_address].numberOfVotesReceived; } function getNumberOfAirlinesFunded() external view requireIsOperational returns(uint256 _count) { return numberOfAirlinesFunded; } function getInsuranceBalance() external view requireIsOperational returns(uint256) { return insuranceBalance; } function getContractBalance() external view requireIsOperational returns(uint256) { return contractBalance; } function registerFlight(bytes32 _key, address _airline, uint256 _flightDateTime, string _flightName, uint8 _statusCode) external requireIsOperational requireIsCallerAuthorized { flights[_key].airline = _airline; flights[_key].flightDateTime = _flightDateTime; flights[_key].flightName = _flightName; flights[_key].statusCode = _statusCode; currentFlights.push(_key); } //register a passenger for a flight function registerPassenger(address _passengerAddress, bytes32 _flightKey) external requireIsOperational requireIsCallerAuthorized { passengers[_passengerAddress].passengerOnFlight[_flightKey] = false; passengers[_passengerAddress].insuranceAmountForFlight[_flightKey] = 0; //set balance to 5 initial. A gift. passengers[_passengerAddress].balance = 5; } //the passenger starts out with 5 ether, so if the passenger is created, then the balance should be > 0 function getPassengerStatus(address _passengerAddress) external requireIsOperational requireIsCallerAuthorized returns(bool) { if (passengers[_passengerAddress].balance > 0) { return true; } return false; } //the passenger starts out with 5 ether, so if the passenger was paid insurance, then the total balance should equal 6.5 function passengerWasPaidInsurance(address _passengerAddress) external requireIsOperational requireIsCallerAuthorized returns(bool) { if (passengers[_passengerAddress].balance > 5) { return true; } return false; } function getFlightData(bytes32 _key) external view requireIsOperational requireIsCallerAuthorized returns(string memory flightName, uint256 flightDateTime, address airline, uint8 status) { require(flights[_key].airline != address(0)); return (flights[_key].flightName, flights[_key].flightDateTime, flights[_key].airline, flights[_key].statusCode); } //get a list of all the current flights function getCurrentFlights() external view requireIsOperational requireIsCallerAuthorized returns (bytes32[] memory ) { return currentFlights; } function setFlightStatus(bytes32 _key, uint8 _status) external requireIsOperational requireIsCallerAuthorized { require(_status != flights[_key].statusCode, "Status code already set"); flights[_key].statusCode = _status; } function isAirlineFunded(address _airline) public view requireIsOperational returns (bool success) { return airlines[_airline].isFunded; } //fund the airline insurance function fundAirlineInsurance(address _airlineAddress, uint256 _fundAmt, uint256 _minFunding) public payable requireIsOperational { airlines[_airlineAddress].funds = airlines[_airlineAddress].funds.add(_fundAmt); if(!airlines[_airlineAddress].isFunded && airlines[_airlineAddress].funds >= _minFunding) { airlines[_airlineAddress].isFunded = true; numberOfAirlinesFunded = numberOfAirlinesFunded.add(1); } contractBalance = contractBalance.add(_fundAmt); } //passenger buys flight insurance function buyFlightInsurance(address _passenger, uint256 _insuranceAmount, bytes32 _flightKey) external payable requireIsOperational { require(!passengers[_passenger].passengerOnFlight[_flightKey], "Passenger already insured"); passengers[_passenger].passengerOnFlight[_flightKey] = true; flights[_flightKey].insuredPassengers.push(_passenger); passengers[_passenger].insuranceAmountForFlight[_flightKey] = _insuranceAmount.div(2) + _insuranceAmount; insuranceBalance = insuranceBalance.add(passengers[_passenger].insuranceAmountForFlight[_flightKey]); contractBalance = contractBalance.sub(_insuranceAmount.div(2)); } //does the passenger have insurance function passengerHasInsurance(address _passenger, bytes32 _flightKey) external view requireIsOperational returns(bool) { return (passengers[_passenger].passengerOnFlight[_flightKey]); } function processPayment(uint256 value) external payable requireIsOperational requireIsCallerAuthorized { contractBalance = contractBalance.add(value); } function() external payable { contractBalance = contractBalance.add(msg.value); } function processFlightStatus(bytes32 _flightKey, bool _wasLateAirline) external requireIsOperational requireIsCallerAuthorized { uint256 passenger; uint256 payableAmount; //if airline was late, then pay insurance to all passengers on the flight if(_wasLateAirline) { for(passenger = 0; passenger < flights[_flightKey].insuredPassengers.length; passenger++) { if(passengers[flights[_flightKey].insuredPassengers[passenger]].passengerOnFlight[_flightKey]) { payableAmount = passengers[flights[_flightKey].insuredPassengers[passenger]].insuranceAmountForFlight[_flightKey]; passengers[flights[_flightKey].insuredPassengers[passenger]].insuranceAmountForFlight[_flightKey] = 0; passengers[flights[_flightKey].insuredPassengers[passenger]].balance = passengers[flights[_flightKey].insuredPassengers[passenger]].balance.add(payableAmount); insuranceBalance = insuranceBalance.sub(payableAmount); } } flights[_flightKey].insuredPassengers.length = 0; } else { for(passenger = 0; passenger < flights[_flightKey].insuredPassengers.length; passenger++) { if(passengers[flights[_flightKey].insuredPassengers[passenger]].passengerOnFlight[_flightKey]) { payableAmount = passengers[flights[_flightKey].insuredPassengers[passenger]].insuranceAmountForFlight[_flightKey]; passengers[flights[_flightKey].insuredPassengers[passenger]].insuranceAmountForFlight[_flightKey] = 0; contractBalance = contractBalance.add(payableAmount); insuranceBalance = insuranceBalance.sub(payableAmount); } } flights[_flightKey].insuredPassengers.length = 0; } } function payoutFunds(address _payee) external payable requireIsOperational requireIsCallerAuthorized { require(passengers[_payee].balance > 0, "Balance must be greater than 0."); uint256 balanceOwed = passengers[_payee].balance; passengers[_payee].balance = 0; _payee.transfer(balanceOwed); } }
passenger buys flight insurance
function buyFlightInsurance(address _passenger, uint256 _insuranceAmount, bytes32 _flightKey) external payable requireIsOperational { require(!passengers[_passenger].passengerOnFlight[_flightKey], "Passenger already insured"); passengers[_passenger].passengerOnFlight[_flightKey] = true; flights[_flightKey].insuredPassengers.push(_passenger); passengers[_passenger].insuranceAmountForFlight[_flightKey] = _insuranceAmount.div(2) + _insuranceAmount; insuranceBalance = insuranceBalance.add(passengers[_passenger].insuranceAmountForFlight[_flightKey]); contractBalance = contractBalance.sub(_insuranceAmount.div(2)); }
6,419,522
[ 1, 5466, 14348, 25666, 1900, 25187, 2763, 295, 1359, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 24243, 5048, 295, 1359, 12, 2867, 389, 5466, 14348, 16, 2254, 5034, 389, 2679, 295, 1359, 6275, 16, 1731, 1578, 389, 19131, 653, 13, 7010, 565, 3903, 7010, 565, 8843, 429, 7010, 565, 2583, 2520, 2988, 287, 203, 377, 288, 203, 3639, 2583, 12, 5, 5466, 275, 6215, 63, 67, 5466, 14348, 8009, 5466, 14348, 1398, 24243, 63, 67, 19131, 653, 6487, 315, 6433, 14348, 1818, 316, 2055, 72, 8863, 203, 3639, 1342, 275, 6215, 63, 67, 5466, 14348, 8009, 5466, 14348, 1398, 24243, 63, 67, 19131, 653, 65, 273, 638, 31, 203, 3639, 1183, 10730, 63, 67, 19131, 653, 8009, 267, 2055, 72, 6433, 275, 6215, 18, 6206, 24899, 5466, 14348, 1769, 203, 3639, 1342, 275, 6215, 63, 67, 5466, 14348, 8009, 2679, 295, 1359, 6275, 1290, 24243, 63, 67, 19131, 653, 65, 273, 389, 2679, 295, 1359, 6275, 18, 2892, 12, 22, 13, 397, 389, 2679, 295, 1359, 6275, 31, 203, 3639, 2763, 295, 1359, 13937, 273, 2763, 295, 1359, 13937, 18, 1289, 12, 5466, 275, 6215, 63, 67, 5466, 14348, 8009, 2679, 295, 1359, 6275, 1290, 24243, 63, 67, 19131, 653, 19226, 203, 3639, 6835, 13937, 273, 6835, 13937, 18, 1717, 24899, 2679, 295, 1359, 6275, 18, 2892, 12, 22, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT-open-group pragma solidity ^0.8.11; import "contracts/libraries/math/CryptoLibrary.sol"; import "contracts/utils/AtomicCounter.sol"; import "contracts/interfaces/IValidatorPool.sol"; import "contracts/interfaces/IETHDKG.sol"; import "contracts/interfaces/IETHDKGEvents.sol"; import "contracts/interfaces/IProxy.sol"; import "contracts/libraries/ethdkg/ETHDKGStorage.sol"; import "contracts/utils/ETHDKGUtils.sol"; import "contracts/utils/ImmutableAuth.sol"; contract ETHDKGMock is ETHDKGStorage, IETHDKG, ETHDKGUtils, ImmutableETHDKGAccusations, ImmutableETHDKGPhases, IETHDKGEvents { address internal immutable _ethdkgAccusations; address internal immutable _ethdkgPhases; constructor() ETHDKGStorage() ImmutableETHDKGAccusations() ImmutableETHDKGPhases() { // bytes32("ETHDKGPhases") = 0x455448444b475068617365730000000000000000000000000000000000000000; address ethdkgPhases = IProxy(_ETHDKGPhasesAddress()).getImplementationAddress(); assembly { if iszero(extcodesize(ethdkgPhases)) { mstore(0x00, "ethdkgPhases size 0") revert(0x00, 0x20) } } _ethdkgPhases = ethdkgPhases; // bytes32("ETHDKGAccusations") = 0x455448444b4741636375736174696f6e73000000000000000000000000000000; address ethdkgAccusations = IProxy(_ETHDKGAccusationsAddress()).getImplementationAddress(); assembly { if iszero(extcodesize(ethdkgAccusations)) { mstore(0x00, "ethdkgAccusations size 0") revert(0x00, 0x20) } } _ethdkgAccusations = ethdkgAccusations; } function initialize(uint256 phaseLength_, uint256 confirmationLength_) public initializer { _phaseLength = uint16(phaseLength_); _confirmationLength = uint16(confirmationLength_); } modifier onlyValidator() { require( IValidatorPool(_ValidatorPoolAddress()).isValidator(msg.sender), "ETHDKG: Only validators allowed!" ); _; } function setPhaseLength(uint16 phaseLength_) external { require( !_isETHDKGRunning(), "ETHDKG: This variable cannot be set if an ETHDKG round is running!" ); _phaseLength = phaseLength_; } function setConfirmationLength(uint16 confirmationLength_) external { require( !_isETHDKGRunning(), "ETHDKG: This variable cannot be set if an ETHDKG round is running!" ); _confirmationLength = confirmationLength_; } function setCustomMadnetHeight(uint256 madnetHeight) external { _customMadnetHeight = madnetHeight; emit ValidatorSetCompleted( 0, _nonce, ISnapshots(_SnapshotsAddress()).getEpoch(), ISnapshots(_SnapshotsAddress()).getCommittedHeightFromLatestSnapshot(), madnetHeight, 0x0, 0x0, 0x0, 0x0 ); } function isETHDKGRunning() public view returns (bool) { return _isETHDKGRunning(); } function _isETHDKGRunning() internal view returns (bool) { // Handling initial case if (_phaseStartBlock == 0) { return false; } return !_isETHDKGCompleted() && !_isETHDKGHalted(); } function isETHDKGCompleted() public view returns (bool) { return _isETHDKGCompleted(); } function _isETHDKGCompleted() internal view returns (bool) { return _ethdkgPhase == Phase.Completion; } function isETHDKGHalted() public view returns (bool) { return _isETHDKGHalted(); } // todo: generate truth table function _isETHDKGHalted() internal view returns (bool) { bool ethdkgFailedInDisputePhase = (_ethdkgPhase == Phase.DisputeShareDistribution || _ethdkgPhase == Phase.DisputeGPKJSubmission) && block.number >= _phaseStartBlock + _phaseLength && _badParticipants != 0; bool ethdkgFailedInNormalPhase = block.number >= _phaseStartBlock + 2 * _phaseLength; return ethdkgFailedInNormalPhase || ethdkgFailedInDisputePhase; } function isMasterPublicKeySet() public view returns (bool) { return ((_masterPublicKey[0] != 0) || (_masterPublicKey[1] != 0) || (_masterPublicKey[2] != 0) || (_masterPublicKey[3] != 0)); } function getNonce() public view returns (uint256) { return _nonce; } function getPhaseStartBlock() public view returns (uint256) { return _phaseStartBlock; } function getPhaseLength() public view returns (uint256) { return _phaseLength; } function getConfirmationLength() public view returns (uint256) { return _confirmationLength; } function getETHDKGPhase() public view returns (Phase) { return _ethdkgPhase; } function getNumParticipants() public view returns (uint256) { return _numParticipants; } function getBadParticipants() public view returns (uint256) { return _badParticipants; } function getMinValidators() public pure returns (uint256) { return MIN_VALIDATOR; } function getParticipantInternalState(address participant) public view returns (Participant memory) { return _participants[participant]; } function getParticipantsInternalState(address[] calldata participantAddresses) public view returns (Participant[] memory) { Participant[] memory participants = new Participant[](participantAddresses.length); for (uint256 i = 0; i < participantAddresses.length; i++) { participants[i] = _participants[participantAddresses[i]]; } return participants; } function tryGetParticipantIndex(address participant) public view returns (bool, uint256) { Participant memory participantData = _participants[participant]; if (participantData.nonce == _nonce && _nonce != 0) { return (true, _participants[participant].index); } return (false, 0); } function getMasterPublicKey() public view returns (uint256[4] memory) { return _masterPublicKey; } function initializeETHDKG() external { _initializeETHDKG(); } function _callAccusationContract(bytes memory callData) internal returns (bytes memory) { (bool success, bytes memory returnData) = _ethdkgAccusations.delegatecall(callData); if (!success) { // solhint-disable no-inline-assembly assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } return returnData; } function _callPhaseContract(bytes memory callData) internal returns (bytes memory) { (bool success, bytes memory returnData) = _ethdkgPhases.delegatecall(callData); if (!success) { // solhint-disable no-inline-assembly assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } return returnData; } function _initializeETHDKG() internal { //todo: should we reward ppl here? uint256 numberValidators = IValidatorPool(_ValidatorPoolAddress()).getValidatorsCount(); require( numberValidators >= MIN_VALIDATOR, "ETHDKG: Minimum number of validators staked not met!" ); _phaseStartBlock = uint64(block.number); _nonce++; _numParticipants = 0; _badParticipants = 0; _mpkG1 = [uint256(0), uint256(0)]; _ethdkgPhase = Phase.RegistrationOpen; delete _masterPublicKey; emit RegistrationOpened( block.number, numberValidators, _nonce, _phaseLength, _confirmationLength ); } function register(uint256[2] memory publicKey) external onlyValidator { _callPhaseContract(abi.encodeWithSignature("register(uint256[2])", publicKey)); } function accuseParticipantNotRegistered(address[] memory dishonestAddresses) external { _callAccusationContract( abi.encodeWithSignature("accuseParticipantNotRegistered(address[])", dishonestAddresses) ); } function distributeShares(uint256[] memory encryptedShares, uint256[2][] memory commitments) external onlyValidator { _callPhaseContract( abi.encodeWithSignature( "distributeShares(uint256[],uint256[2][])", encryptedShares, commitments ) ); } /// function accuseParticipantDidNotDistributeShares(address[] memory dishonestAddresses) external { _callAccusationContract( abi.encodeWithSignature( "accuseParticipantDidNotDistributeShares(address[])", dishonestAddresses ) ); } // Someone sent bad shares function accuseParticipantDistributedBadShares( address dishonestAddress, uint256[] memory encryptedShares, uint256[2][] memory commitments, uint256[2] memory sharedKey, uint256[2] memory sharedKeyCorrectnessProof ) external onlyValidator { _callAccusationContract( abi.encodeWithSignature( "accuseParticipantDistributedBadShares(address,uint256[],uint256[2][],uint256[2],uint256[2])", dishonestAddress, encryptedShares, commitments, sharedKey, sharedKeyCorrectnessProof ) ); } function submitKeyShare( uint256[2] memory keyShareG1, uint256[2] memory keyShareG1CorrectnessProof, uint256[4] memory keyShareG2 ) external onlyValidator { _callPhaseContract( abi.encodeWithSignature( "submitKeyShare(uint256[2],uint256[2],uint256[4])", keyShareG1, keyShareG1CorrectnessProof, keyShareG2 ) ); } function accuseParticipantDidNotSubmitKeyShares(address[] memory dishonestAddresses) external { _callAccusationContract( abi.encodeWithSignature( "accuseParticipantDidNotSubmitKeyShares(address[])", dishonestAddresses ) ); } function submitMasterPublicKey(uint256[4] memory masterPublicKey_) external { _callPhaseContract( abi.encodeWithSignature("submitMasterPublicKey(uint256[4])", masterPublicKey_) ); } function submitGPKJ(uint256[4] memory gpkj) external onlyValidator { _callPhaseContract(abi.encodeWithSignature("submitGPKJ(uint256[4])", gpkj)); } function accuseParticipantDidNotSubmitGPKJ(address[] memory dishonestAddresses) external { _callAccusationContract( abi.encodeWithSignature( "accuseParticipantDidNotSubmitGPKJ(address[])", dishonestAddresses ) ); } function accuseParticipantSubmittedBadGPKJ( address[] memory validators, bytes32[] memory encryptedSharesHash, uint256[2][][] memory commitments, address dishonestAddress ) external onlyValidator { _callAccusationContract( abi.encodeWithSignature( "accuseParticipantSubmittedBadGPKJ(address[],bytes32[],uint256[2][][],address)", validators, encryptedSharesHash, commitments, dishonestAddress ) ); } // Successful_Completion should be called at the completion of the DKG algorithm. function complete() external { _callPhaseContract(abi.encodeWithSignature("complete()")); } function minorSlash(address validator, address accussator) external { IValidatorPool(_ValidatorPoolAddress()).minorSlash(validator, accussator); } function majorSlash(address validator, address accussator) external { IValidatorPool(_ValidatorPoolAddress()).majorSlash(validator, accussator); } function setConsensusRunning() external { IValidatorPool(_ValidatorPoolAddress()).completeETHDKG(); } }
Handling initial case
function _isETHDKGRunning() internal view returns (bool) { if (_phaseStartBlock == 0) { return false; } return !_isETHDKGCompleted() && !_isETHDKGHalted(); }
1,826,900
[ 1, 14701, 2172, 648, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 291, 1584, 44, 3398, 43, 7051, 1435, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 67, 13961, 1685, 1768, 422, 374, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 3639, 327, 401, 67, 291, 1584, 44, 3398, 43, 9556, 1435, 597, 401, 67, 291, 1584, 44, 3398, 16715, 287, 2344, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x9368A0BDA86742Dc3E96140B4bD99eC86e0a1E3e/sources/contracts/module/NTS-Multi.sol
* @dev Check if the player needs to refresh their staking status./
function chkRefresh(address player, uint16 _staketeam) internal view returns (bool) { NTSUserManager.StakeTMHC memory _inStakedtmhc = userStorage.getStakedTMHC(_staketeam); if(!chkLeaderOwner(player, _staketeam) && _inStakedtmhc.stakeowner == player){ return true; } NTSUserManager.StakeTeam memory _inStakedteam = userStorage.getInStakedTeam(_staketeam); uint16[] memory _boostIds = _inStakedteam.boostIds; for(uint16 i = 0; i < _boostIds.length; i++) { uint16 _boostId = _boostIds[i]; NTSUserManager.StakeMOMO memory _inStakedmomo = userStorage.getStakedMOMO(_boostId); if(!chkBoostOwner(player, _boostId) && _inStakedmomo.stakeowner == player){ return true; } } return false; } Team Stake / Rewards / unStake cycle
7,047,276
[ 1, 1564, 309, 326, 7291, 4260, 358, 4460, 3675, 384, 6159, 1267, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15000, 8323, 12, 2867, 7291, 16, 2254, 2313, 389, 334, 581, 278, 3820, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 423, 8047, 1299, 1318, 18, 510, 911, 22903, 23408, 3778, 389, 267, 510, 9477, 16925, 28353, 273, 729, 3245, 18, 588, 510, 9477, 22903, 23408, 24899, 334, 581, 278, 3820, 1769, 203, 3639, 309, 12, 5, 27038, 15254, 5541, 12, 14872, 16, 389, 334, 581, 278, 3820, 13, 597, 389, 267, 510, 9477, 16925, 28353, 18, 334, 911, 8443, 422, 7291, 15329, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 203, 3639, 423, 8047, 1299, 1318, 18, 510, 911, 8689, 3778, 389, 267, 510, 9477, 10035, 273, 729, 3245, 18, 588, 382, 510, 9477, 8689, 24899, 334, 581, 278, 3820, 1769, 203, 3639, 2254, 2313, 8526, 3778, 389, 25018, 2673, 273, 389, 267, 510, 9477, 10035, 18, 25018, 2673, 31, 203, 3639, 364, 12, 11890, 2313, 277, 273, 374, 31, 277, 411, 389, 25018, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2254, 2313, 389, 25018, 548, 273, 389, 25018, 2673, 63, 77, 15533, 203, 5411, 423, 8047, 1299, 1318, 18, 510, 911, 49, 1872, 51, 3778, 389, 267, 510, 9477, 81, 362, 83, 273, 729, 3245, 18, 588, 510, 9477, 49, 1872, 51, 24899, 25018, 548, 1769, 203, 5411, 309, 12, 5, 27038, 26653, 5541, 12, 14872, 16, 389, 25018, 548, 13, 597, 389, 267, 510, 9477, 81, 362, 83, 18, 334, 911, 8443, 422, 7291, 15329, 203, 7734, 327, 638, 31, 203, 5411, 289, 203, 2 ]
pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. * * Subtraction and addition only here. */ 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 unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title A contract for generating unique identifiers for any requests. * @dev Any contract that supports requesting inherits this contract to * ensure request to be unique. */ contract RequestUid { /** * MEMBER: counter for request. */ uint256 public requestCount; /** * CONSTRUCTOR: initial counter with 0. */ constructor() public { requestCount = 0; } /** * METHOD: generate a new identifier. * @dev 3 parameters as inputs: * 1. blockhash of previous block; * 2. the address of the initialized contract which is requested; * 3. the value of counter. * @return a 32-byte uid. */ function generateRequestUid() internal returns (bytes32 uid) { return keccak256(abi.encodePacked(blockhash(block.number - uint256(1)), address(this), ++requestCount)); } } /** * @dev This contract makes the inheritor have the functionality if the * inheritor authorize the admin. */ contract AdminUpgradeable is RequestUid { /** * Event * @dev After requesting of admin change, emit an event. */ event AdminChangeRequested(bytes32 _uid, address _msgSender, address _newAdmin); /** * Event * @dev After confirming a request of admin change, emit an event. */ event AdminChangeConfirmed(bytes32 _uid, address _newAdmin); /** * STRUCT: A struct defined to store an request of admin change. */ struct AdminChangeRequest { address newAdminAddress; } /** * MEMBER: admin address(account address or contract address) which * is authorize by the inheritor. */ address public admin; /** * MEMBER: a list of requests submitted. */ mapping (bytes32 => AdminChangeRequest) public adminChangeReqs; /** * MODIFIER: The operations from admin is allowed only. */ modifier adminOperations { require(msg.sender == admin, "admin can call this method only"); _; } /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public RequestUid() { admin = _admin; } /** * METHOD: Upgrade the admin ---- request. * @dev Request changing the admin address authorized. * Anyone can call this method to submit a request to change * the admin address. It will be pending until admin address * comfirming the request, and the admin changes. * @param _newAdmin The address of new admin, account or contract. * @return uid The unique id of the request. */ function requestAdminChange(address _newAdmin) public returns (bytes32 uid) { require(_newAdmin != address(0), "admin is not 0 address"); uid = generateRequestUid(); adminChangeReqs[uid] = AdminChangeRequest({ newAdminAddress: _newAdmin }); emit AdminChangeRequested(uid, msg.sender, _newAdmin); } /** * METHOD: Upgrade the admin ---- confirm. * @dev Confirm a reqeust of admin change storing in the mapping * of `adminChangeReqs`. The operation is authorized to the old * admin only. The new admin will be authorized after the method * called successfully. * @param _uid The uid of request to change admin. */ function confirmAdminChange(bytes32 _uid) public adminOperations { admin = getAdminChangeReq(_uid); delete adminChangeReqs[_uid]; emit AdminChangeConfirmed(_uid, admin); } /** * METHOD: Get the address of an admin request by uid. * @dev It is a private method which gets address of an admin * in the mapping `adminChangeReqs` * @param _uid The uid of request to change admin. * @return _newAdminAddress The address of new admin in the pending requests */ function getAdminChangeReq(bytes32 _uid) private view returns (address _newAdminAddress) { AdminChangeRequest storage changeRequest = adminChangeReqs[_uid]; require(changeRequest.newAdminAddress != address(0)); return changeRequest.newAdminAddress; } } /** * @dev This is a contract which will be inherited by BICAProxy and BICALedger. */ contract BICALogicUpgradeable is AdminUpgradeable { /** * Event * @dev After requesting of logic contract address change, emit an event. */ event LogicChangeRequested(bytes32 _uid, address _msgSender, address _newLogic); /** * Event * @dev After confirming a request of logic contract address change, emit an event. */ event LogicChangeConfirmed(bytes32 _uid, address _newLogic); /** * STRUCT: A struct defined to store an request of Logic contract address change. */ struct LogicChangeRequest { address newLogicAddress; } /** * MEMBER: BICALogic address(a contract address) which implements logics of token. */ BICALogic public bicaLogic; /** * MEMBER: a list of requests of logic change submitted */ mapping (bytes32 => LogicChangeRequest) public logicChangeReqs; /** * MODIFIER: The call from bicaLogic is allowed only. */ modifier onlyLogic { require(msg.sender == address(bicaLogic), "only logic contract is authorized"); _; } /** * CONSTRUCTOR: Initialize with an admin address which is authorized to change * the value of bicaLogic. */ constructor (address _admin) public AdminUpgradeable(_admin) { bicaLogic = BICALogic(0x0); } /** * METHOD: Upgrade the logic contract ---- request. * @dev Request changing the logic contract address authorized. * Anyone can call this method to submit a request to change * the logic address. It will be pending until admin address * comfirming the request, and the logic contract address changes, i.e. * the value of bicaLogic changes. * @param _newLogic The address of new logic contract. * @return uid The unique id of the request. */ function requestLogicChange(address _newLogic) public returns (bytes32 uid) { require(_newLogic != address(0), "new logic address can not be 0"); uid = generateRequestUid(); logicChangeReqs[uid] = LogicChangeRequest({ newLogicAddress: _newLogic }); emit LogicChangeRequested(uid, msg.sender, _newLogic); } /** * METHOD: Upgrade the logic contract ---- confirm. * @dev Confirm a reqeust of logic contract change storing in the * mapping of `logicChangeReqs`. The operation is authorized to * the admin only. * @param _uid The uid of request to change logic contract. */ function confirmLogicChange(bytes32 _uid) public adminOperations { bicaLogic = getLogicChangeReq(_uid); delete logicChangeReqs[_uid]; emit LogicChangeConfirmed(_uid, address(bicaLogic)); } /** * METHOD: Get the address of an logic contract address request by uid. * @dev It is a private method which gets address of an address * in the mapping `adminChangeReqs` * @param _uid The uid of request to change logic contract address. * @return _newLogicAddress The address of new logic contract address * in the pending requests */ function getLogicChangeReq(bytes32 _uid) private view returns (BICALogic _newLogicAddress) { LogicChangeRequest storage changeRequest = logicChangeReqs[_uid]; require(changeRequest.newLogicAddress != address(0)); return BICALogic(changeRequest.newLogicAddress); } } /** * @dev This contract is the core contract of all logic. It links `bicaProxy` * and `bicaLedger`. It implements the issue of new amount of token, burn some * value of someone's token. */ contract BICALogic is AdminUpgradeable { using SafeMath for uint256; /** * Event * @dev After issuing an ammout of BICA, emit an event for the value of requester. */ event Requester(address _supplyAddress, address _receiver, uint256 _valueRequested); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying margin. */ event PayMargin(address _supplyAddress, address _marginAddress, uint256 _marginValue); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying interest. */ event PayInterest(address _supplyAddress, address _interestAddress, uint256 _interestValue); /** * Event * @dev After issuing an ammout of BICA, emit an event of paying multi fee. */ event PayMultiFee(address _supplyAddress, address _feeAddress, uint256 _feeValue); /** * Event * @dev After freezing a user address, emit an event in logic contract. */ event AddressFrozenInLogic(address indexed addr); /** * Event * @dev After unfreezing a user address, emit an event in logic contract. */ event AddressUnfrozenInLogic(address indexed addr); /** * MEMBER: A reference to the proxy contract. * It links the proxy contract in one direction. */ BICAProxy public bicaProxy; /** * MEMBER: A reference to the ledger contract. * It links the ledger contract in one direction. */ BICALedger public bicaLedger; /** * MODIFIER: The call from bicaProxy is allowed only. */ modifier onlyProxy { require(msg.sender == address(bicaProxy), "only the proxy contract allowed only"); _; } /** * CONSTRUCTOR: Initialize with the proxy contract address, the ledger * contract and an admin address. */ constructor (address _bicaProxy, address _bicaLedger, address _admin) public AdminUpgradeable(_admin) { bicaProxy = BICAProxy(_bicaProxy); bicaLedger = BICALedger(_bicaLedger); } /** * METHOD: `approve` operation in logic contract. * @dev Receive the call request of `approve` from proxy contract and * request approve operation to ledger contract. Need to check the sender * and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function approveWithSender(address _sender, address _spender, uint256 _value) public onlyProxy returns (bool success){ require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); bicaLedger.setAllowance(_sender, _spender, _value); bicaProxy.emitApproval(_sender, _spender, _value); return true; } /** * METHOD: Core logic of the `increaseApproval` method in proxy contract. * @dev Receive the call request of `increaseApproval` from proxy contract * and request increasing value of allownce to ledger contract. Need to * check the sender * and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function increaseApprovalWithSender(address _sender, address _spender, uint256 _addedValue) public onlyProxy returns (bool success) { require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); uint256 currentAllowance = bicaLedger.allowed(_sender, _spender); uint256 newAllowance = currentAllowance.add(_addedValue); require(newAllowance >= currentAllowance); bicaLedger.setAllowance(_sender, _spender, newAllowance); bicaProxy.emitApproval(_sender, _spender, newAllowance); return true; } /** * METHOD: Core logic of the `decreaseApproval` method in proxy contract. * @dev Receive the call request of `decreaseApproval` from proxy contract * and request decreasing value of allownce to ledger contract. Need to * check the sender and spender are not frozen * @param _sender The address initiating the approval in proxy. * @return success or not. */ function decreaseApprovalWithSender(address _sender, address _spender, uint256 _subtractedValue) public onlyProxy returns (bool success) { require(_spender != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool spenderFrozen = bicaLedger.getFrozenByAddress(_spender); require(!spenderFrozen, "Spender is frozen"); uint256 currentAllowance = bicaLedger.allowed(_sender, _spender); uint256 newAllowance = currentAllowance.sub(_subtractedValue); require(newAllowance <= currentAllowance); bicaLedger.setAllowance(_sender, _spender, newAllowance); bicaProxy.emitApproval(_sender, _spender, newAllowance); return true; } /** * METHOD: Core logic of comfirming request of issuetoken to a specified receiver. * @dev Admin can issue an ammout of BICA only. * @param _requesterAccount The address of request account. * @param _requestValue The value of requester. * @param _marginAccount The address of margin account. * @param _marginValue The value of token to pay to margin account. * @param _interestAccount The address accepting interest. * @param _interestValue The value of interest. * @param _otherFeeAddress The address accepting multi fees. * @param _otherFeeValue The value of other fees. */ function issue(address _requesterAccount, uint256 _requestValue, address _marginAccount, uint256 _marginValue, address _interestAccount, uint256 _interestValue, address _otherFeeAddress, uint256 _otherFeeValue) public adminOperations { require(_requesterAccount != address(0)); require(_marginAccount != address(0)); require(_interestAccount != address(0)); require(_otherFeeAddress != address(0)); require(!bicaLedger.getFrozenByAddress(_requesterAccount), "Requester is frozen"); require(!bicaLedger.getFrozenByAddress(_marginAccount), "Margin account is frozen"); require(!bicaLedger.getFrozenByAddress(_interestAccount), "Interest account is frozen"); require(!bicaLedger.getFrozenByAddress(_otherFeeAddress), "Other fee account is frozen"); uint256 requestTotalValue = _marginValue.add(_interestValue).add(_otherFeeValue).add(_requestValue); uint256 supply = bicaLedger.totalSupply(); uint256 newSupply = supply.add(requestTotalValue); if (newSupply >= supply) { bicaLedger.setTotalSupply(newSupply); bicaLedger.addBalance(_marginAccount, _marginValue); bicaLedger.addBalance(_interestAccount, _interestValue); if ( _otherFeeValue > 0 ){ bicaLedger.addBalance(_otherFeeAddress, _otherFeeValue); } bicaLedger.addBalance(_requesterAccount, _requestValue); emit Requester(msg.sender, _requesterAccount, _requestValue); emit PayMargin(msg.sender, _marginAccount, _marginValue); emit PayInterest(msg.sender, _interestAccount, _interestValue); emit PayMultiFee(msg.sender, _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _marginAccount, _marginValue); bicaProxy.emitTransfer(address(0), _interestAccount, _interestValue); bicaProxy.emitTransfer(address(0), _otherFeeAddress, _otherFeeValue); bicaProxy.emitTransfer(address(0), _requesterAccount, _requestValue); } } /** * METHOD: Burn the specified value of the message sender's balance. * @dev Admin can call this method to burn some amount of BICA. * @param _value The amount of token to be burned. * @return success or not. */ function burn(uint256 _value) public adminOperations returns (bool success) { bool burnerFrozen = bicaLedger.getFrozenByAddress(msg.sender); require(!burnerFrozen, "Burner is frozen"); uint256 balanceOfSender = bicaLedger.balances(msg.sender); require(_value <= balanceOfSender); bicaLedger.setBalance(msg.sender, balanceOfSender.sub(_value)); bicaLedger.setTotalSupply(bicaLedger.totalSupply().sub(_value)); bicaProxy.emitTransfer(msg.sender, address(0), _value); return true; } /** * METHOD: Freeze a user address. * @dev Admin can call this method to freeze a user account. * @param _user user address. */ function freeze(address _user) public adminOperations { require(_user != address(0), "the address to be frozen cannot be 0"); bicaLedger.freezeByAddress(_user); emit AddressFrozenInLogic(_user); } /** * METHOD: Unfreeze a user address. * @dev Admin can call this method to unfreeze a user account. * @param _user user address. */ function unfreeze(address _user) public adminOperations { require(_user != address(0), "the address to be unfrozen cannot be 0"); bicaLedger.unfreezeByAddress(_user); emit AddressUnfrozenInLogic(_user); } /** * METHOD: Core logic of `transferFrom` interface method in ERC20 token standard. * @dev It can only be called by the `bicaProxy` contract. * @param _sender The address initiating the approval in proxy. * @return success or not. */ function transferFromWithSender(address _sender, address _from, address _to, uint256 _value) public onlyProxy returns (bool success){ require(_to != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "Sender is frozen"); bool fromFrozen = bicaLedger.getFrozenByAddress(_from); require(!fromFrozen, "`from` is frozen"); bool toFrozen = bicaLedger.getFrozenByAddress(_to); require(!toFrozen, "`to` is frozen"); uint256 balanceOfFrom = bicaLedger.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = bicaLedger.allowed(_from, _sender); require(_value <= senderAllowance); bicaLedger.setBalance(_from, balanceOfFrom.sub(_value)); bicaLedger.addBalance(_to, _value); bicaLedger.setAllowance(_from, _sender, senderAllowance.sub(_value)); bicaProxy.emitTransfer(_from, _to, _value); return true; } /** * METHOD: Core logic of `transfer` interface method in ERC20 token standard. * @dev It can only be called by the `bicaProxy` contract. * @param _sender The address initiating the approval in proxy. * @return success or not. */ function transferWithSender(address _sender, address _to, uint256 _value) public onlyProxy returns (bool success){ require(_to != address(0)); bool senderFrozen = bicaLedger.getFrozenByAddress(_sender); require(!senderFrozen, "sender is frozen"); bool toFrozen = bicaLedger.getFrozenByAddress(_to); require(!toFrozen, "to is frozen"); uint256 balanceOfSender = bicaLedger.balances(_sender); require(_value <= balanceOfSender); bicaLedger.setBalance(_sender, balanceOfSender.sub(_value)); bicaLedger.addBalance(_to, _value); bicaProxy.emitTransfer(_sender, _to, _value); return true; } /** * METHOD: Core logic of `totalSupply` interface method in ERC20 token standard. */ function totalSupply() public view returns (uint256) { return bicaLedger.totalSupply(); } /** * METHOD: Core logic of `balanceOf` interface method in ERC20 token standard. */ function balanceOf(address _owner) public view returns (uint256 balance) { return bicaLedger.balances(_owner); } /** * METHOD: Core logic of `allowance` interface method in ERC20 token standard. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return bicaLedger.allowed(_owner, _spender); } } /** * @dev This contract is the core storage contract of ERC20 token ledger. * It defines some operations of data in the storage. */ contract BICALedger is BICALogicUpgradeable { using SafeMath for uint256; /** * MEMBER: The total supply of the token. */ uint256 public totalSupply; /** * MEMBER: The mapping of balance of users. */ mapping (address => uint256) public balances; /** * MEMBER: The mapping of allowance of users. */ mapping (address => mapping (address => uint256)) public allowed; /** * MEMBER: The mapping of frozen addresses. */ mapping(address => bool) public frozen; /** * Event * @dev After freezing a user address, emit an event in ledger contract. */ event AddressFrozen(address indexed addr); /** * Event * @dev After unfreezing a user address, emit an event in ledger contract. */ event AddressUnfrozen(address indexed addr); /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public BICALogicUpgradeable(_admin) { totalSupply = 0; } /** * METHOD: Check an address is frozen or not. * @dev check an address is frozen or not. It can be call by logic contract only. * @param _user user addree. */ function getFrozenByAddress(address _user) public view onlyLogic returns (bool frozenOrNot) { // frozenOrNot = false; return frozen[_user]; } /** * METHOD: Freeze an address. * @dev Freeze an address. It can be called by logic contract only. * @param _user user addree. */ function freezeByAddress(address _user) public onlyLogic { require(!frozen[_user], "user already frozen"); frozen[_user] = true; emit AddressFrozen(_user); } /** * METHOD: Unfreeze an address. * @dev Unfreeze an address. It can be called by logic contract only. * @param _user user addree. */ function unfreezeByAddress(address _user) public onlyLogic { require(frozen[_user], "address already unfrozen"); frozen[_user] = false; emit AddressUnfrozen(_user); } /** * METHOD: Set `totalSupply` in the ledger contract. * @dev It will be called when a new issue is confirmed. It can be called * by logic contract only. * @param _newTotalSupply The value of new total supply. */ function setTotalSupply(uint256 _newTotalSupply) public onlyLogic { totalSupply = _newTotalSupply; } /** * METHOD: Set allowance for owner to a spender in the ledger contract. * @dev It will be called when the owner modify the allowance to the * spender. It can be called by logic contract only. * @param _owner The address allow spender to spend. * @param _spender The address allowed to spend. * @param _value The limit of how much can be spent by `_spender`. */ function setAllowance(address _owner, address _spender, uint256 _value) public onlyLogic { allowed[_owner][_spender] = _value; } /** * METHOD: Set balance of the owner in the ledger contract. * @dev It will be called when the owner modify the balance of owner * in logic. It can be called by logic contract only. * @param _owner The address who owns the balance. * @param _newBalance The balance to be set. */ function setBalance(address _owner, uint256 _newBalance) public onlyLogic { balances[_owner] = _newBalance; } /** * METHOD: Add balance of the owner in the ledger contract. * @dev It will be called when the balance of owner increases. * It can be called by logic contract only. * @param _owner The address who owns the balance. * @param _balanceIncrease The balance to be add. */ function addBalance(address _owner, uint256 _balanceIncrease) public onlyLogic { balances[_owner] = balances[_owner].add(_balanceIncrease); } } contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @dev This contract is a viewer of ERC20 token standard. * It includes no logic and data. */ contract BICAProxy is ERC20Interface, BICALogicUpgradeable { /** * MEMBER: The name of the token. */ string public name; /** * MEMBER: The symbol of the token. */ string public symbol; /** * MEMBER: The number of decimals of the token. */ uint public decimals; /** * CONSTRUCTOR: Initialize with an admin address. */ constructor (address _admin) public BICALogicUpgradeable(_admin){ name = "BitCapital Coin"; symbol = 'BICA'; decimals = 2; } /** * METHOD: Get `totalSupply` of token. * @dev It is the standard method of ERC20. * @return The total token supply. */ function totalSupply() public view returns (uint256) { return bicaLogic.totalSupply(); } /** * METHOD: Get the balance of a owner. * @dev It is the standard method of ERC20. * @return The balance of a owner. */ function balanceOf(address _owner) public view returns (uint256 balance) { return bicaLogic.balanceOf(_owner); } /** * METHOD: Emit a Transfer event in proxy contract. */ function emitTransfer(address _from, address _to, uint256 _value) public onlyLogic { emit Transfer(_from, _to, _value); } /** * METHOD: The message sender sends some amount of token to receiver. * @dev It will call the logic contract to send some token to receiver. * It is the standard method of ERC20. * @return success or not */ function transfer(address _to, uint256 _value) public returns (bool success) { return bicaLogic.transferWithSender(msg.sender, _to, _value); } /** * METHOD: Transfer amount of tokens from `_from` to `_to`. * @dev It is the standard method of ERC20. * @return success or not */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return bicaLogic.transferFromWithSender(msg.sender, _from, _to, _value); } /** * METHOD: Emit a Approval event in proxy contract. */ function emitApproval(address _owner, address _spender, uint256 _value) public onlyLogic { emit Approval(_owner, _spender, _value); } /** * METHOD: Allow `_spender` to be able to spend `_value` token. * @dev It is the standard method of ERC20. * @return success or not */ function approve(address _spender, uint256 _value) public returns (bool success) { return bicaLogic.approveWithSender(msg.sender, _spender, _value); } /** * METHOD: Increase allowance value of message sender to `_spender`. * @return success or not */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return bicaLogic.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** * METHOD: Decrease allowance value of message sender to `_spender`. * @return success or not */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return bicaLogic.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** * METHOD: Return the allowance value of `_owner` to `_spender`. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return bicaLogic.allowance(_owner, _spender); } }
* CONSTRUCTOR: Initialize with an admin address which is authorized to change the value of bicaLogic./
constructor (address _admin) public AdminUpgradeable(_admin) { bicaLogic = BICALogic(0x0); }
2,479,114
[ 1, 26935, 916, 30, 9190, 598, 392, 3981, 1758, 1492, 353, 10799, 358, 2549, 326, 460, 434, 324, 26433, 20556, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 261, 2867, 389, 3666, 13, 1071, 7807, 10784, 429, 24899, 3666, 13, 288, 203, 3639, 324, 26433, 20556, 273, 605, 10109, 717, 335, 12, 20, 92, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.10; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositFunding} from "./DepositFunding.sol"; import {DepositRedemption} from "./DepositRedemption.sol"; import {DepositStates} from "./DepositStates.sol"; import "../system/DepositFactoryAuthority.sol"; contract Deposit is DepositFactoryAuthority { using DepositRedemption for DepositUtils.Deposit; using DepositFunding for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; DepositUtils.Deposit self; // We separate the constructor from createNewDeposit to make proxy factories easier /* solium-disable-next-line no-empty-blocks */ constructor () public {} function () external payable {} /// @notice Get the integer representing the current state /// @dev We implement this because contracts don't handle foreign enums well /// @return The 0-indexed state from the DepositStates enum function getCurrentState() public view returns (uint256) { return uint256(self.currentState); } /// @notice Check if the Deposit is in ACTIVE state. /// @return True if state is ACTIVE, fale otherwise. function inActive() public view returns (bool) { return self.inActive(); } /// @notice Retrieve the remaining term of the deposit in seconds. /// @dev The value is not guaranteed since block.timestmap can be lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at term function remainingTerm() public view returns(uint256){ return self.remainingTerm(); } /// @notice Get the signer fee for the Deposit. /// @return Fee amount in TBTC function signerFee() public view returns (uint256) { return self.signerFee(); } /// @notice Get the Deposit BTC lot size. /// @return uint256 lot size in satoshi function lotSizeSatoshis() public view returns (uint256){ return self.lotSizeSatoshis; } /// @notice Get the Deposit ERC20 lot size. /// @return uint256 lot size in erc20 decimal (max 18) function lotSizeTbtc() public view returns (uint256){ return self.lotSizeTbtc(); } /// @notice Get the size of the funding UTXO. /// @return Uint256 UTXO size. function utxoSize() public view returns (uint256){ return self.utxoSize(); } // THIS IS THE INIT FUNCTION /// @notice The system can spin up a new deposit /// @dev This should be called by an approved contract, not a developer /// @param _m m for m-of-n /// @param _m n for m-of-n /// @return True if successful, otherwise revert function createNewDeposit( address _TBTCSystem, address _TBTCToken, address _TBTCDepositToken, address _FeeRebateToken, address _VendingMachine, uint256 _m, uint256 _n, uint256 _lotSize ) public onlyFactory payable returns (bool) { self.TBTCSystem = _TBTCSystem; self.TBTCToken = _TBTCToken; self.TBTCDepositToken = _TBTCDepositToken; self.FeeRebateToken = _FeeRebateToken; self.VendingMachine = _VendingMachine; self.createNewDeposit(_m, _n, _lotSize); return true; } /// @notice Anyone can request redemption /// @dev The redeemer specifies details about the Bitcoin redemption tx /// @param _outputValueBytes The 8-byte LE output size /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @return True if successful, otherwise revert function requestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public returns (bool) { self.requestRedemption(_outputValueBytes, _redeemerOutputScript); return true; } /// @notice Anyone can request redemption /// @dev The redeemer specifies details about the Bitcoin redemption tx and pays for the redemption /// @param _outputValueBytes The 8-byte LE output size /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public returns (bool) { self.transferAndRequestRedemption( _outputValueBytes, _redeemerOutputScript, _finalRecipient ); return true; } /// @notice Get TBTC amount required by redemption by a specified _redeemer /// @dev Will revert if redemption is not possible by msg.sender. /// @param _redeemer The deposit redeemer. /// @return The amount in TBTC needed to redeem the deposit. function getRedemptionTbtcRequirement(address _redeemer) public view returns(uint256){ return self.getRedemptionTbtcRequirement(_redeemer); } /// @notice Get TBTC amount required for redemption assuming _redeemer /// is this deposit's TDT owner. /// @param _redeemer The assumed owner of the deposit's TDT /// @return The amount in TBTC needed to redeem the deposit. function getOwnerRedemptionTbtcRequirement(address _redeemer) public view returns(uint256){ return self.getOwnerRedemptionTbtcRequirement(_redeemer); } /// @notice Anyone may provide a withdrawal signature if it was requested /// @dev The signers will be penalized if this (or provideRedemptionProof) is not called /// @param _v Signature recovery value /// @param _r Signature R value /// @param _s Signature S value /// @return True if successful, False if prevented by timeout, otherwise revert function provideRedemptionSignature( uint8 _v, bytes32 _r, bytes32 _s ) public returns (bool) { self.provideRedemptionSignature(_v, _r, _s); return true; } /// @notice Anyone may notify the contract that a fee bump is needed /// @dev This sends us back to AWAITING_WITHDRAWAL_SIGNATURE /// @param _previousOutputValueBytes The previous output's value /// @param _newOutputValueBytes The new output's value /// @return True if successful, False if prevented by timeout, otherwise revert function increaseRedemptionFee( bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public returns (bool) { return self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes); } /// @notice Anyone may provide a withdrawal proof to prove redemption /// @dev The signers will be penalized if this is not called /// @param _txVersion Transaction version number (4-byte LE) /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs /// @param _txLocktime Final 4 bytes of the transaction /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed) /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers function provideRedemptionProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public returns (bool) { self.provideRedemptionProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); return true; } /// @notice Anyone may notify the contract that the signers have failed to produce a signature /// @dev This is considered fraud, and is punished /// @return True if successful, otherwise revert function notifySignatureTimeout() public returns (bool) { self.notifySignatureTimeout(); return true; } /// @notice Anyone may notify the contract that the signers have failed to produce a redemption proof /// @dev This is considered fraud, and is punished /// @return True if successful, otherwise revert function notifyRedemptionProofTimeout() public returns (bool) { self.notifyRedemptionProofTimeout(); return true; } // // FUNDING FLOW // /// @notice Anyone may notify the contract that signing group setup has timed out /// @dev We rely on the keep system punishes the signers in this case /// @return True if successful, otherwise revert function notifySignerSetupFailure() public returns (bool) { self.notifySignerSetupFailure(); return true; } /// @notice we poll the Keep contract to retrieve our pubkey /// @dev We store the pubkey as 2 bytestrings, X and Y. /// @return True if successful, otherwise revert function retrieveSignerPubkey() public returns (bool) { self.retrieveSignerPubkey(); return true; } /// @notice Anyone may notify the contract that the funder has failed to send BTC /// @dev This is considered a funder fault, and we revoke their bond /// @return True if successful, otherwise revert function notifyFundingTimeout() public returns (bool) { self.notifyFundingTimeout(); return true; } /// @notice Anyone can provide a signature that was not requested to prove fraud during funding /// @dev ECDSA is NOT SECURE unless you verify the digest /// @param _v Signature recovery value /// @param _r Signature R value /// @param _s Signature S value /// @param _signedDigest The digest signed by the signature vrs tuple /// @param _preimage The sha256 preimage of the digest /// @return True if successful, otherwise revert function provideFundingECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public returns (bool) { self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); return true; } /// @notice Anyone may notify the contract no funding proof was submitted during funding fraud /// @dev This is not a funder fault. The signers have faulted, so the funder shouldn't fund /// @return True if successful, otherwise revert function notifyFraudFundingTimeout() public returns (bool) { self.notifyFraudFundingTimeout(); return true; } /// @notice Anyone may notify the deposit of a funding proof during funding fraud // We reward the funder the entire bond if this occurs /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding /// @param _txVersion Transaction version number (4-byte LE) /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs /// @param _txLocktime Final 4 bytes of the transaction /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed) /// @param _merkleProof The merkle proof of transaction inclusion in a block /// @param _txIndexInBlock Transaction index in the block (0-indexed) /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first /// @return True if no errors are thrown function provideFraudBTCFundingProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public returns (bool) { self.provideFraudBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); return true; } /// @notice Anyone may notify the deposit of a funding proof to activate the deposit /// This is the happy-path of the funding flow. It means that we have succeeded /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding /// @param _txVersion Transaction version number (4-byte LE) /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs /// @param _txLocktime Final 4 bytes of the transaction /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed) /// @param _merkleProof The merkle proof of transaction inclusion in a block /// @param _txIndexInBlock Transaction index in the block (0-indexed) /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first /// @return True if no errors are thrown function provideBTCFundingProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public returns (bool) { self.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); return true; } // // FRAUD // /// @notice Anyone can provide a signature that was not requested to prove fraud /// @dev ECDSA is NOT SECURE unless you verify the digest /// @param _v Signature recovery value /// @param _r Signature R value /// @param _s Signature S value /// @param _signedDigest The digest signed by the signature vrs tuple /// @param _preimage The sha256 preimage of the digest /// @return True if successful, otherwise revert function provideECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public returns (bool) { self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); return true; } /// @notice Anyone may notify the deposit of fraud via an SPV proof /// @dev We strong prefer ECDSA fraud proofs /// @param _txVersion Transaction version number (4-byte LE) /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs /// @param _txLocktime Final 4 bytes of the transaction /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed) /// @param _targetInputIndex Index of the input that spends the custodied UTXO /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers /// @return True if successful, otherwise revert function provideSPVFraudProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, uint8 _targetInputIndex, bytes memory _bitcoinHeaders ) public returns (bool) { self.provideSPVFraudProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _merkleProof, _txIndexInBlock, _targetInputIndex, _bitcoinHeaders ); return true; } // // LIQUIDATION // /// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud /// @dev For interface, reading auctionValue will give a past value. the current is better /// @return True if successful, revert otherwise function purchaseSignerBondsAtAuction() public returns (bool) { self.purchaseSignerBondsAtAuction(); return true; } /// @notice Notify the contract that the signers are undercollateralized /// @dev Calls out to the system for oracle info /// @return True if successful, otherwise revert function notifyCourtesyCall() public returns (bool) { self.notifyCourtesyCall(); return true; } /// @notice Goes from courtesy call to active /// @dev Only callable if collateral is sufficient and the deposit is not expiring /// @return True if successful, otherwise revert function exitCourtesyCall() public returns (bool) { self.exitCourtesyCall(); return true; } /// @notice Notify the contract that the signers are undercollateralized /// @dev Calls out to the system for oracle info /// @return True if successful, otherwise revert function notifyUndercollateralizedLiquidation() public returns (bool) { self.notifyUndercollateralizedLiquidation(); return true; } /// @notice Notifies the contract that the courtesy period has elapsed /// @dev This is treated as an abort, rather than fraud /// @return True if successful, otherwise revert function notifyCourtesyTimeout() public returns (bool) { self.notifyCourtesyTimeout(); return true; } /// @notice Notifies the contract that its term limit has been reached /// @dev This initiates a courtesy call /// @return True if successful, otherwise revert function notifyDepositExpiryCourtesyCall() public returns (bool) { self.notifyDepositExpiryCourtesyCall(); return true; } }
@notice Anyone may notify the deposit of fraud via an SPV proof @dev We strong prefer ECDSA fraud proofs @param _txVersion Transaction version number (4-byte LE) @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs @param _txLocktime Final 4 bytes of the transaction @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed) @param _targetInputIndex Index of the input that spends the custodied UTXO @param _bitcoinHeaders An array of tightly-packed bitcoin headers @return True if successful, otherwise revert
function provideSPVFraudProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, uint8 _targetInputIndex, bytes memory _bitcoinHeaders ) public returns (bool) { self.provideSPVFraudProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _merkleProof, _txIndexInBlock, _targetInputIndex, _bitcoinHeaders ); return true; }
1,057,139
[ 1, 2961, 476, 2026, 5066, 326, 443, 1724, 434, 284, 354, 1100, 3970, 392, 11405, 58, 14601, 15604, 1660, 11773, 13256, 7773, 19748, 284, 354, 1100, 14601, 87, 282, 389, 978, 1444, 3639, 5947, 1177, 1300, 261, 24, 17, 7229, 5380, 13, 282, 389, 978, 1210, 5018, 565, 4826, 2492, 4540, 26989, 635, 326, 1300, 434, 4540, 3749, 487, 279, 4562, 1702, 16, 943, 374, 92, 4488, 12, 2947, 22, 13, 4540, 282, 389, 978, 1447, 5018, 282, 4826, 2492, 6729, 26989, 635, 326, 1300, 434, 6729, 3749, 487, 279, 4562, 1702, 16, 943, 374, 92, 4488, 12, 2947, 22, 13, 6729, 282, 389, 978, 2531, 957, 4202, 16269, 1059, 1731, 434, 326, 2492, 282, 389, 6592, 15609, 20439, 1377, 1021, 30235, 14601, 434, 26485, 434, 326, 2229, 316, 326, 25851, 1203, 282, 389, 978, 1016, 382, 1768, 282, 1021, 770, 434, 326, 2229, 316, 326, 24420, 1203, 261, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 5615, 3118, 58, 42, 354, 1100, 20439, 12, 203, 3639, 1731, 24, 389, 978, 1444, 16, 203, 3639, 1731, 3778, 389, 978, 1210, 5018, 16, 203, 3639, 1731, 3778, 389, 978, 1447, 5018, 16, 203, 3639, 1731, 24, 389, 978, 2531, 957, 16, 203, 3639, 1731, 3778, 389, 6592, 15609, 20439, 16, 203, 3639, 2254, 5034, 389, 978, 1016, 382, 1768, 16, 203, 3639, 2254, 28, 389, 3299, 1210, 1016, 16, 203, 3639, 1731, 3778, 389, 3682, 12645, 3121, 203, 565, 262, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 365, 18, 685, 6768, 3118, 58, 42, 354, 1100, 20439, 12, 203, 5411, 389, 978, 1444, 16, 203, 5411, 389, 978, 1210, 5018, 16, 203, 5411, 389, 978, 1447, 5018, 16, 203, 5411, 389, 978, 2531, 957, 16, 203, 5411, 389, 6592, 15609, 20439, 16, 203, 5411, 389, 978, 1016, 382, 1768, 16, 203, 5411, 389, 3299, 1210, 1016, 16, 203, 5411, 389, 3682, 12645, 3121, 203, 3639, 11272, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 // MgvOfferMaking.sol // Copyright (C) 2021 Giry SAS. // // 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.8.10; pragma abicoder v2; import {IMaker, HasMgvEvents, P} from "./MgvLib.sol"; import {MgvHasOffers} from "./MgvHasOffers.sol"; /* `MgvOfferMaking` contains market-making-related functions. */ contract MgvOfferMaking is MgvHasOffers { using P.Offer for P.Offer.t; using P.OfferDetail for P.OfferDetail.t; using P.Global for P.Global.t; using P.Local for P.Local.t; /* # Public Maker operations ## New Offer */ //+clear+ /* In the Mangrove, makers and takers call separate functions. Market makers call `newOffer` to fill the book, and takers call functions such as `marketOrder` to consume it. */ //+clear+ /* The following structs holds offer creation/update parameters in memory. This frees up stack space for local variables. */ struct OfferPack { address outbound_tkn; address inbound_tkn; uint wants; uint gives; uint id; uint gasreq; uint gasprice; uint pivotId; P.Global.t global; P.Local.t local; // used on update only P.Offer.t oldOffer; } /* The function `newOffer` is for market makers only; no match with the existing book is done. A maker specifies how much `inbound_tkn` it `wants` and how much `outbound_tkn` it `gives`. It also specify with `gasreq` how much gas should be given when executing their offer. `gasprice` indicates an upper bound on the gasprice at which the maker is ready to be penalised if their offer fails. Any value below the Mangrove's internal `gasprice` configuration value will be ignored. `gasreq`, together with `gasprice`, will contribute to determining the penalty provision set aside by the Mangrove from the market maker's `balanceOf` balance. Offers are always inserted at the correct place in the book. This requires walking through offers to find the correct insertion point. As in [Oasis](https://github.com/daifoundation/maker-otc/blob/f2060c5fe12fe3da71ac98e8f6acc06bca3698f5/src/matching_market.sol#L493), the maker should find the id of an offer close to its own and provide it as `pivotId`. An offer cannot be inserted in a closed market, nor when a reentrancy lock for `outbound_tkn`,`inbound_tkn` is on. No more than $2^{32}-1$ offers can ever be created for one `outbound_tkn`,`inbound_tkn` pair. The actual contents of the function is in `writeOffer`, which is called by both `newOffer` and `updateOffer`. */ function newOffer( address outbound_tkn, address inbound_tkn, uint wants, uint gives, uint gasreq, uint gasprice, uint pivotId ) external payable returns (uint) { unchecked { /* In preparation for calling `writeOffer`, we read the `outbound_tkn`,`inbound_tkn` pair configuration, check for reentrancy and market liveness, fill the `OfferPack` struct and increment the `outbound_tkn`,`inbound_tkn` pair's `last`. */ OfferPack memory ofp; (ofp.global, ofp.local) = config(outbound_tkn, inbound_tkn); unlockedMarketOnly(ofp.local); activeMarketOnly(ofp.global, ofp.local); if (msg.value > 0) { creditWei(msg.sender, msg.value); } ofp.id = 1 + ofp.local.last(); require(uint32(ofp.id) == ofp.id, "mgv/offerIdOverflow"); ofp.local = ofp.local.last(ofp.id); ofp.outbound_tkn = outbound_tkn; ofp.inbound_tkn = inbound_tkn; ofp.wants = wants; ofp.gives = gives; ofp.gasreq = gasreq; ofp.gasprice = gasprice; ofp.pivotId = pivotId; /* The second parameter to writeOffer indicates that we are creating a new offer, not updating an existing one. */ writeOffer(ofp, false); /* Since we locally modified a field of the local configuration (`last`), we save the change to storage. Note that `writeOffer` may have further modified the local configuration by updating the current `best` offer. */ locals[ofp.outbound_tkn][ofp.inbound_tkn] = ofp.local; return ofp.id; }} /* ## Update Offer */ //+clear+ /* Very similar to `newOffer`, `updateOffer` prepares an `OfferPack` for `writeOffer`. Makers should use it for updating live offers, but also to save on gas by reusing old, already consumed offers. A `pivotId` should still be given to minimise reads in the offer book. It is OK to give the offers' own id as a pivot. Gas use is minimal when: 1. The offer does not move in the book 2. The offer does not change its `gasreq` 3. The (`outbound_tkn`,`inbound_tkn`)'s `offer_gasbase` has not changed since the offer was last written 4. `gasprice` has not changed since the offer was last written 5. `gasprice` is greater than the Mangrove's gasprice estimation */ function updateOffer( address outbound_tkn, address inbound_tkn, uint wants, uint gives, uint gasreq, uint gasprice, uint pivotId, uint offerId ) external payable { unchecked { OfferPack memory ofp; (ofp.global, ofp.local) = config(outbound_tkn, inbound_tkn); unlockedMarketOnly(ofp.local); activeMarketOnly(ofp.global, ofp.local); if (msg.value > 0) { creditWei(msg.sender, msg.value); } ofp.outbound_tkn = outbound_tkn; ofp.inbound_tkn = inbound_tkn; ofp.wants = wants; ofp.gives = gives; ofp.id = offerId; ofp.gasreq = gasreq; ofp.gasprice = gasprice; ofp.pivotId = pivotId; ofp.oldOffer = offers[outbound_tkn][inbound_tkn][offerId]; // Save local config P.Local.t oldLocal = ofp.local; /* The second argument indicates that we are updating an existing offer, not creating a new one. */ writeOffer(ofp, true); /* We saved the current pair's configuration before calling `writeOffer`, since that function may update the current `best` offer. We now check for any change to the configuration and update it if needed. */ if (!oldLocal.eq(ofp.local)) { locals[ofp.outbound_tkn][ofp.inbound_tkn] = ofp.local; } }} /* ## Retract Offer */ //+clear+ /* `retractOffer` takes the offer `offerId` out of the book. However, `deprovision == true` also refunds the provision associated with the offer. */ function retractOffer( address outbound_tkn, address inbound_tkn, uint offerId, bool deprovision ) external returns (uint provision) { unchecked { (, P.Local.t local) = config(outbound_tkn, inbound_tkn); unlockedMarketOnly(local); P.Offer.t offer = offers[outbound_tkn][inbound_tkn][offerId]; P.OfferDetail.t offerDetail = offerDetails[outbound_tkn][inbound_tkn][offerId]; require( msg.sender == offerDetail.maker(), "mgv/retractOffer/unauthorized" ); /* Here, we are about to un-live an offer, so we start by taking it out of the book by stitching together its previous and next offers. Note that unconditionally calling `stitchOffers` would break the book since it would connect offers that may have since moved. */ if (isLive(offer)) { P.Local.t oldLocal = local; local = stitchOffers( outbound_tkn, inbound_tkn, offer.prev(), offer.next(), local ); /* If calling `stitchOffers` has changed the current `best` offer, we update the storage. */ if (!oldLocal.eq(local)) { locals[outbound_tkn][inbound_tkn] = local; } } /* Set `gives` to 0. Moreover, the last argument depends on whether the user wishes to get their provision back (if true, `gasprice` will be set to 0 as well). */ dirtyDeleteOffer( outbound_tkn, inbound_tkn, offerId, offer, offerDetail, deprovision ); /* If the user wants to get their provision back, we compute its provision from the offer's `gasprice`, `offer_gasbase` and `gasreq`. */ if (deprovision) { provision = 10**9 * offerDetail.gasprice() * //gasprice is 0 if offer was deprovisioned (offerDetail.gasreq() + offerDetail.offer_gasbase()); // credit `balanceOf` and log transfer creditWei(msg.sender, provision); } emit OfferRetract(outbound_tkn, inbound_tkn, offerId); }} /* ## Provisioning Market makers must have enough provisions for possible penalties. These provisions are in ETH. Every time a new offer is created or an offer is updated, `balanceOf` is adjusted to provision the offer's maximum possible penalty (`gasprice * (gasreq + offer_gasbase)`). For instance, if the current `balanceOf` of a maker is 1 ether and they create an offer that requires a provision of 0.01 ethers, their `balanceOf` will be reduced to 0.99 ethers. No ethers will move; this is just an internal accounting movement to make sure the maker cannot `withdraw` the provisioned amounts. */ //+clear+ /* Fund should be called with a nonzero value (hence the `payable` modifier). The provision will be given to `maker`, not `msg.sender`. */ function fund(address maker) public payable { unchecked { (P.Global.t _global, ) = config(address(0), address(0)); liveMgvOnly(_global); creditWei(maker, msg.value); }} function fund() external payable { unchecked { fund(msg.sender); }} /* A transfer with enough gas to the Mangrove will increase the caller's available `balanceOf` balance. _You should send enough gas to execute this function when sending money to the Mangrove._ */ receive() external payable { unchecked { fund(msg.sender); }} /* Any provision not currently held to secure an offer's possible penalty is available for withdrawal. */ function withdraw(uint amount) external returns (bool noRevert) { unchecked { /* Since we only ever send money to the caller, we do not need to provide any particular amount of gas, the caller should manage this herself. */ debitWei(msg.sender, amount); (noRevert, ) = msg.sender.call{value: amount}(""); }} /* # Low-level Maker functions */ /* ## Write Offer */ function writeOffer(OfferPack memory ofp, bool update) internal { unchecked { /* `gasprice`'s floor is Mangrove's own gasprice estimate, `ofp.global.gasprice`. We first check that gasprice fits in 16 bits. Otherwise it could be that `uint16(gasprice) < global_gasprice < gasprice`, and the actual value we store is `uint16(gasprice)`. */ require( checkGasprice(ofp.gasprice), "mgv/writeOffer/gasprice/16bits" ); if (ofp.gasprice < ofp.global.gasprice()) { ofp.gasprice = ofp.global.gasprice(); } /* * Check `gasreq` below limit. Implies `gasreq` at most 24 bits wide, which ensures no overflow in computation of `provision` (see below). */ require( ofp.gasreq <= ofp.global.gasmax(), "mgv/writeOffer/gasreq/tooHigh" ); /* * Make sure `gives > 0` -- division by 0 would throw in several places otherwise, and `isLive` relies on it. */ require(ofp.gives > 0, "mgv/writeOffer/gives/tooLow"); /* * Make sure that the maker is posting a 'dense enough' offer: the ratio of `outbound_tkn` offered per gas consumed must be high enough. The actual gas cost paid by the taker is overapproximated by adding `offer_gasbase` to `gasreq`. */ require( ofp.gives >= (ofp.gasreq + ofp.local.offer_gasbase()) * ofp.local.density(), "mgv/writeOffer/density/tooLow" ); /* The following checks are for the maker's convenience only. */ require(uint96(ofp.gives) == ofp.gives, "mgv/writeOffer/gives/96bits"); require(uint96(ofp.wants) == ofp.wants, "mgv/writeOffer/wants/96bits"); /* The position of the new or updated offer is found using `findPosition`. If the offer is the best one, `prev == 0`, and if it's the last in the book, `next == 0`. `findPosition` is only ever called here, but exists as a separate function to make the code easier to read. **Warning**: `findPosition` will call `better`, which may read the offer's `offerDetails`. So it is important to find the offer position _before_ we update its `offerDetail` in storage. We waste 1 (hot) read in that case but we deem that the code would get too ugly if we passed the old `offerDetail` as argument to `findPosition` and to `better`, just to save 1 hot read in that specific case. */ (uint prev, uint next) = findPosition(ofp); /* Log the write offer event. */ emit OfferWrite( ofp.outbound_tkn, ofp.inbound_tkn, msg.sender, ofp.wants, ofp.gives, ofp.gasprice, ofp.gasreq, ofp.id, prev ); /* We now write the new `offerDetails` and remember the previous provision (0 by default, for new offers) to balance out maker's `balanceOf`. */ uint oldProvision; { P.OfferDetail.t offerDetail = offerDetails[ofp.outbound_tkn][ofp.inbound_tkn][ ofp.id ]; if (update) { require( msg.sender == offerDetail.maker(), "mgv/updateOffer/unauthorized" ); oldProvision = 10**9 * offerDetail.gasprice() * (offerDetail.gasreq() + offerDetail.offer_gasbase()); } /* If the offer is new, has a new `gasprice`, `gasreq`, or if the Mangrove's `offer_gasbase` configuration parameter has changed, we also update `offerDetails`. */ if ( !update || offerDetail.gasreq() != ofp.gasreq || offerDetail.gasprice() != ofp.gasprice || offerDetail.offer_gasbase() != ofp.local.offer_gasbase() ) { uint offer_gasbase = ofp.local.offer_gasbase(); offerDetails[ofp.outbound_tkn][ofp.inbound_tkn][ofp.id] = P.OfferDetail.pack({ __maker: msg.sender, __gasreq: ofp.gasreq, __offer_gasbase: offer_gasbase, __gasprice: ofp.gasprice }); } } /* With every change to an offer, a maker may deduct provisions from its `balanceOf` balance. It may also get provisions back if the updated offer requires fewer provisions than before. */ { uint provision = (ofp.gasreq + ofp.local.offer_gasbase()) * ofp.gasprice * 10**9; if (provision > oldProvision) { debitWei(msg.sender, provision - oldProvision); } else if (provision < oldProvision) { creditWei(msg.sender, oldProvision - provision); } } /* We now place the offer in the book at the position found by `findPosition`. */ /* First, we test if the offer has moved in the book or is not currently in the book. If `!isLive(ofp.oldOffer)`, we must update its prev/next. If it is live but its prev has changed, we must also update them. Note that checking both `prev = oldPrev` and `next == oldNext` would be redundant. If either is true, then the updated offer has not changed position and there is nothing to update. As a note for future changes, there is a tricky edge case where `prev == oldPrev` yet the prev/next should be changed: a previously-used offer being brought back in the book, and ending with the same prev it had when it was in the book. In that case, the neighbor is currently pointing to _another_ offer, and thus must be updated. With the current code structure, this is taken care of as a side-effect of checking `!isLive`, but should be kept in mind. The same goes in the `next == oldNext` case. */ if (!isLive(ofp.oldOffer) || prev != ofp.oldOffer.prev()) { /* * If the offer is not the best one, we update its predecessor; otherwise we update the `best` value. */ if (prev != 0) { offers[ofp.outbound_tkn][ofp.inbound_tkn][prev] = offers[ofp.outbound_tkn][ofp.inbound_tkn][prev].next(ofp.id); } else { ofp.local = ofp.local.best(ofp.id); } /* * If the offer is not the last one, we update its successor. */ if (next != 0) { offers[ofp.outbound_tkn][ofp.inbound_tkn][next] = offers[ofp.outbound_tkn][ofp.inbound_tkn][next].prev(ofp.id); } /* * Recall that in this branch, the offer has changed location, or is not currently in the book. If the offer is not new and already in the book, we must remove it from its previous location by stitching its previous prev/next. */ if (update && isLive(ofp.oldOffer)) { ofp.local = stitchOffers( ofp.outbound_tkn, ofp.inbound_tkn, ofp.oldOffer.prev(), ofp.oldOffer.next(), ofp.local ); } } /* With the `prev`/`next` in hand, we finally store the offer in the `offers` map. */ P.Offer.t ofr = P.Offer.pack({ __prev: prev, __next: next, __wants: ofp.wants, __gives: ofp.gives }); offers[ofp.outbound_tkn][ofp.inbound_tkn][ofp.id] = ofr; }} /* ## Find Position */ /* `findPosition` takes a price in the form of a (`ofp.wants`,`ofp.gives`) pair, an offer id (`ofp.pivotId`) and walks the book from that offer (backward or forward) until the right position for the price is found. The position is returned as a `(prev,next)` pair, with `prev` or `next` at 0 to mark the beginning/end of the book (no offer ever has id 0). If prices are equal, `findPosition` will put the newest offer last. */ function findPosition(OfferPack memory ofp) internal view returns (uint, uint) { unchecked { uint prevId; uint nextId; uint pivotId = ofp.pivotId; /* Get `pivot`, optimizing for the case where pivot info is already known */ P.Offer.t pivot = pivotId == ofp.id ? ofp.oldOffer : offers[ofp.outbound_tkn][ofp.inbound_tkn][pivotId]; /* In case pivotId is not an active offer, it is unusable (since it is out of the book). We default to the current best offer. If the book is empty pivot will be 0. That is handled through a test in the `better` comparison function. */ if (!isLive(pivot)) { pivotId = ofp.local.best(); pivot = offers[ofp.outbound_tkn][ofp.inbound_tkn][pivotId]; } /* * Pivot is better than `wants/gives`, we follow `next`. */ if (better(ofp, pivot, pivotId)) { P.Offer.t pivotNext; while (pivot.next() != 0) { uint pivotNextId = pivot.next(); pivotNext = offers[ofp.outbound_tkn][ofp.inbound_tkn][pivotNextId]; if (better(ofp, pivotNext, pivotNextId)) { pivotId = pivotNextId; pivot = pivotNext; } else { break; } } // gets here on empty book (prevId, nextId) = (pivotId, pivot.next()); /* * Pivot is strictly worse than `wants/gives`, we follow `prev`. */ } else { P.Offer.t pivotPrev; while (pivot.prev() != 0) { uint pivotPrevId = pivot.prev(); pivotPrev = offers[ofp.outbound_tkn][ofp.inbound_tkn][pivotPrevId]; if (better(ofp, pivotPrev, pivotPrevId)) { break; } else { pivotId = pivotPrevId; pivot = pivotPrev; } } (prevId, nextId) = (pivot.prev(), pivotId); } return ( prevId == ofp.id ? ofp.oldOffer.prev() : prevId, nextId == ofp.id ? ofp.oldOffer.next() : nextId ); }} /* ## Better */ /* The utility method `better` takes an offer represented by `ofp` and another represented by `offer1`. It returns true iff `offer1` is better or as good as `ofp`. "better" is defined on the lexicographic order $\textrm{price} \times_{\textrm{lex}} \textrm{density}^{-1}$. This means that for the same price, offers that deliver more volume per gas are taken first. In addition to `offer1`, we also provide its id, `offerId1` in order to save gas. If necessary (ie. if the prices `wants1/gives1` and `wants2/gives2` are the same), we read storage to get `gasreq1` at `offerDetails[...][offerId1]. */ function better( OfferPack memory ofp, P.Offer.t offer1, uint offerId1 ) internal view returns (bool) { unchecked { if (offerId1 == 0) { /* Happens on empty book. Returning `false` would work as well due to specifics of `findPosition` but true is more consistent. Here we just want to avoid reading `offerDetail[...][0]` for nothing. */ return true; } uint wants1 = offer1.wants(); uint gives1 = offer1.gives(); uint wants2 = ofp.wants; uint gives2 = ofp.gives; uint weight1 = wants1 * gives2; uint weight2 = wants2 * gives1; if (weight1 == weight2) { uint gasreq1 = offerDetails[ofp.outbound_tkn][ofp.inbound_tkn][offerId1].gasreq(); uint gasreq2 = ofp.gasreq; return (gives1 * gasreq2 >= gives2 * gasreq1); } else { return weight1 < weight2; } }} }
/ We saved the current pair's configuration before calling `writeOffer`, since that function may update the current `best` offer. We now check for any change to the configuration and update it if needed. */
function updateOffer( address outbound_tkn, address inbound_tkn, uint wants, uint gives, uint gasreq, uint gasprice, uint pivotId, uint offerId ) external payable { unchecked { OfferPack memory ofp; (ofp.global, ofp.local) = config(outbound_tkn, inbound_tkn); unlockedMarketOnly(ofp.local); activeMarketOnly(ofp.global, ofp.local); if (msg.value > 0) { creditWei(msg.sender, msg.value); } ofp.outbound_tkn = outbound_tkn; ofp.inbound_tkn = inbound_tkn; ofp.wants = wants; ofp.gives = gives; ofp.id = offerId; ofp.gasreq = gasreq; ofp.gasprice = gasprice; ofp.pivotId = pivotId; ofp.oldOffer = offers[outbound_tkn][inbound_tkn][offerId]; if (!oldLocal.eq(ofp.local)) { locals[ofp.outbound_tkn][ofp.inbound_tkn] = ofp.local; } }}
5,357,001
[ 1, 19, 1660, 5198, 326, 783, 3082, 1807, 1664, 1865, 4440, 1375, 2626, 10513, 9191, 3241, 716, 445, 2026, 1089, 326, 783, 1375, 12729, 68, 10067, 18, 1660, 2037, 866, 364, 1281, 2549, 358, 326, 1664, 471, 1089, 518, 309, 3577, 18, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 10513, 12, 203, 565, 1758, 11663, 67, 16099, 82, 16, 203, 565, 1758, 13357, 67, 16099, 82, 16, 203, 565, 2254, 14805, 16, 203, 565, 2254, 14758, 16, 203, 565, 2254, 16189, 3658, 16, 203, 565, 2254, 16189, 8694, 16, 203, 565, 2254, 9939, 548, 16, 203, 565, 2254, 10067, 548, 203, 225, 262, 3903, 8843, 429, 288, 22893, 288, 203, 565, 25753, 4420, 3778, 434, 84, 31, 203, 565, 261, 792, 84, 18, 6347, 16, 434, 84, 18, 3729, 13, 273, 642, 12, 659, 3653, 67, 16099, 82, 16, 13357, 67, 16099, 82, 1769, 203, 565, 25966, 3882, 278, 3386, 12, 792, 84, 18, 3729, 1769, 203, 565, 2695, 3882, 278, 3386, 12, 792, 84, 18, 6347, 16, 434, 84, 18, 3729, 1769, 203, 565, 309, 261, 3576, 18, 1132, 405, 374, 13, 288, 203, 1377, 12896, 3218, 77, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 565, 434, 84, 18, 659, 3653, 67, 16099, 82, 273, 11663, 67, 16099, 82, 31, 203, 565, 434, 84, 18, 267, 3653, 67, 16099, 82, 273, 13357, 67, 16099, 82, 31, 203, 565, 434, 84, 18, 91, 4388, 273, 14805, 31, 203, 565, 434, 84, 18, 75, 3606, 273, 14758, 31, 203, 565, 434, 84, 18, 350, 273, 10067, 548, 31, 203, 565, 434, 84, 18, 31604, 3658, 273, 16189, 3658, 31, 203, 565, 434, 84, 18, 31604, 8694, 273, 16189, 8694, 31, 203, 565, 434, 84, 18, 27306, 548, 273, 9939, 548, 31, 203, 565, 434, 84, 2 ]
pragma solidity ^0.4.21; import "./lib.sol"; import "./participant.sol" as ParticipantContract; import "./investment.sol"; contract RunningTontine { uint constant ONE_YEAR_IN_SECONDS = 31536000; struct Participant { // The share the participant holds in the tontine uint256 share; // Whether the participant has collected their share in this run bool hasCollected; // Whether the participant is still a valid member of the tontine bool remains; // Gimmicky flag to determine if it exists in the mapping bool exists; } // Controls the current state of the tontine enum State { // Money is currently with investment target INVESTING, // Contract has begun paying out PAYING_OUT } // Initially, the tontine is in the investment phase State state = State.INVESTING; // The address of the initial tontine contract address initialTontineAddress; // The address of the contract where the money is invested address investmentAddress; // The timestamp we used on launch uint launchTs; // The interval until the next payout in seconds uint payoutIntervalInSeconds; // The period of time participants have to collect their money uint payoutPeriod; // Mapping of the share of all current participants in the tontine // A non-zero value here implies that a participant is still in the tontine mapping ( address => Participant ) participants; // Iterable list of addresses of all participants // To prevent traversals, participants are NOT removed when devolved - check remains flag instead address[] public participantsList; // Participant count to allow traversal uint numParticipants = 0; // Number of ACTIVE participants - again, prevent traversals uint numActiveParticipants = 0; // The pot of money taken from participants that have been devolved uint pot = 0; // Addresses that have been verified and their identity tokens mapping ( address => bytes32 ) verifiedIdentities; constructor(address _investmentAddress) public { launchTs = now; investmentAddress = _investmentAddress; payoutIntervalInSeconds = launchTs + ONE_YEAR_IN_SECONDS; // Seed the investment target with our initial investment investmentAddress.transfer(address(this).balance); } // TODO: work out how to timer this function endPayoutPeriod() public { // TODO: require the message comes from the timer require(state == State.PAYING_OUT); // Expire any participants that have not collected for (uint i = 0; i < numParticipants; i++) { if (!participants[participantsList[i]].hasCollected) { devolve(participantsList[i]); } participants[participantsList[i]].hasCollected = false; } // Return any uncollected dividends to the investment pool investmentAddress.transfer(address(this).balance); state = State.INVESTING; } // Receive dividends from the investment contract function receiveReturnOnInvestment() external payable { require(msg.sender == investmentAddress); state = State.PAYING_OUT; uint expiry = now + payoutPeriod; // Notify all surviving participants that their funds are ready to collect for (uint i = 0; i < numParticipants; i++) { if (participants[participantsList[i]].remains) { ParticipantContract.Participant(participantsList[i]).notify(expiry); } } } // Add a new participant to the running tontine function addParticipant(address _participant, uint256 _share) external { require(msg.sender == initialTontineAddress); participants[_participant] = Participant({ share: _share, hasCollected: false, remains: true, exists: true }); participantsList.push(_participant); numParticipants++; numActiveParticipants++; } // Called by a participant attempting to retrieve funds from this running tontine function retrieve(bytes32 identityToken) external payable { require(state == State.PAYING_OUT); require(participants[msg.sender].exists); // Verify that we have an identity token and it matches require(identityToken == verifiedIdentities[msg.sender]); // Calculate the dividend - their original share plus their bonus share of the empty pot uint originalShare = address(this).balance / participants[msg.sender].share; uint bonus = pot / numActiveParticipants; // Return` the users' calculated dividend msg.sender.transfer(originalShare + bonus); } // Remove a participant from the tontine and devolve their share to surviving participants function devolve(address participant) internal { emit Devolve(participant); // Notify the participant contract they have been cut out of the contract ParticipantContract.Participant(participantsList[i]).devolve(); // Modify their remnant flag participants[participant].remains = false; // Move their share to the pot pot += participants[participant].share; participants[participant].share = 0; // Remove them from the active participant count numActiveParticipants--; // If there's only one active participant left, it's time to wrap up the contract if (numActiveParticipants == 1) { // Can't tell who's active and who's not, so traverse // TODO: do we need to avoid the traversal? for (uint i = 0; i < numParticipants; i++) { if (participants[participantsList[i]].remains) { wrapUp(participantsList[i]); } } } } // The running tontine has devolved to the final participant // Wrap up the tontine and return all our funds to the originator function wrapUp(address _survivor) internal { emit WrapUp(_survivor, now); Investment(investmentAddress).end(); // Bye! selfdestruct(_survivor); } event Devolve(address); event WrapUp(address survivor, uint ts); }
TODO: work out how to timer this TODO: require the message comes from the timer Expire any participants that have not collected
function endPayoutPeriod() public { require(state == State.PAYING_OUT); for (uint i = 0; i < numParticipants; i++) { if (!participants[participantsList[i]].hasCollected) { devolve(participantsList[i]); } participants[participantsList[i]].hasCollected = false; } state = State.INVESTING; }
15,781,014
[ 1, 6241, 30, 1440, 596, 3661, 358, 5441, 333, 2660, 30, 2583, 326, 883, 14535, 628, 326, 5441, 7784, 577, 1281, 22346, 716, 1240, 486, 12230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 679, 52, 2012, 5027, 1435, 1071, 288, 203, 3639, 2583, 12, 2019, 422, 3287, 18, 11389, 1360, 67, 5069, 1769, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 818, 1988, 27620, 31, 277, 27245, 288, 203, 5411, 309, 16051, 2680, 27620, 63, 2680, 27620, 682, 63, 77, 65, 8009, 5332, 10808, 329, 13, 288, 203, 7734, 4461, 5390, 12, 2680, 27620, 682, 63, 77, 19226, 203, 5411, 289, 203, 5411, 22346, 63, 2680, 27620, 682, 63, 77, 65, 8009, 5332, 10808, 329, 273, 629, 31, 203, 3639, 289, 203, 203, 203, 3639, 919, 273, 3287, 18, 706, 3412, 882, 1360, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x8b35c25eD7f60bDeCacA2AC093f1DC8522642B48/sources/src/lender/tranche.sol
@notice returns total supply of tokens issued by the tranche @return totalSupply_ total supply of tokens
function tokenSupply() external view returns (uint256 totalSupply_) { return token.totalSupply(); }
8,342,311
[ 1, 6154, 2078, 14467, 434, 2430, 16865, 635, 326, 13637, 18706, 327, 2078, 3088, 1283, 67, 2078, 14467, 434, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 2078, 3088, 1283, 67, 13, 288, 203, 3639, 327, 1147, 18, 4963, 3088, 1283, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract Election { // Model a base USER struct user { // Admin has the UserId 1 uint256 id; address add; string name; // string C_pwd; // string profile_path; string email; // Permissions:- 0: Voter, 1: Candidate, 2: Admin int256 permissions; uint256 cand_index; string pwd; } struct candidate { uint256 C_id; uint256 vote_count; string C_name; uint256 E_id; // C_info: Achievements, clubs etc. string C_info; bool deleted; } struct election { uint256 E_id; string E_name; // time will be stored in seconds on blockchain, and JS will handle it accordingly. // Campaigning time will start just after time for candidate registration is over and // will end 24 hrs prior to polling uint256 time_cand_register_end; uint256 time_polling_starts; uint256 time_polling_ends; bool deleted; } struct report { uint256 reportId; uint256 E_id; uint256 reported_user; string reason; } struct voter { uint256 id; uint256 E_id; bool voted; bool reportedByUser; bool blacklisted_by_admin; bool deleted; } struct campaign { uint256 id; string description; // string description; uint256 c_id; uint256 E_id; string name; // bool deleted; } event trigger_event(); // event CampaignCreated( // uint256 id, // string hash, // // string description, // uint256 c_id, // uint256 E_id, // string name // ); //Fetch Campaign Data mapping(uint256 => campaign) public campaigns; // Store Campaign Count uint256 public campaign_count = 0; // Fetch Users mapping(uint256 => user) public users; //addresses mapping with ids mapping(address => uint256) public addresses; // store elections mapping(uint256 => election) public elections; mapping(uint256 => voter) public voterlist; mapping(uint256 => report) public reports; // Array of candidate struct to store candidates candidate[] public candidates; // voted event // event votedEvent(uint256 indexed _C_id); // Store Candidates Count uint256 public user_count = 0; uint256 public voter_list_count = 0; // Store Eletions Count uint256 public election_count = 0; uint256 public report_count = 0; // Add elections // Remember election_count is same as E_id for a particular election. function add_election( string memory _E_name, uint256 _time_cand_register_end, uint256 _time_polling_starts, uint256 _time_polling_ends ) public { // Check in JS that the time entered are accordingly after the current time. // i.e current_time < cand_time < poll_start < poll_end; election_count++; elections[election_count].E_id = election_count; elections[election_count].E_name = _E_name; elections[election_count] .time_cand_register_end = _time_cand_register_end; elections[election_count].time_polling_starts = _time_polling_starts; elections[election_count].time_polling_ends = _time_polling_ends; // Call the event emit trigger_event(); } // Edit elections // Remember election_count is same as E_id for a particular election. function edit_election( uint256 _E_id, string memory _E_name, uint256 _time_cand_register_end, uint256 _time_polling_starts, uint256 _time_polling_ends ) public { // elections[election_count].E_id = election_count; elections[_E_id].E_name = _E_name; elections[_E_id].time_cand_register_end = _time_cand_register_end; elections[_E_id].time_polling_starts = _time_polling_starts; elections[_E_id].time_polling_ends = _time_polling_ends; // Call the event emit trigger_event(); } function report_by_user( uint256 _reportedUser, uint256 _E_id, string memory _reason ) public { uint256 i; for (i = 1; i <= voter_list_count; i++) { if ( voterlist[i].id == _reportedUser && voterlist[i].E_id == _E_id ) { require( !voterlist[i].reportedByUser, "User is already reported" ); require( !voterlist[i].reportedByUser, "User wasn't reported earlier" ); voterlist[i].reportedByUser = true; } } report_count++; reports[report_count].reportId = report_count; reports[report_count].E_id = _E_id; reports[report_count].reported_user = _reportedUser; reports[report_count].reason = _reason; // Call the event emit trigger_event(); } function blacklist_by_admin(uint256 _id, uint256 _E_id) public { uint256 i; for (i = 1; i <= voter_list_count; i++) { if (voterlist[i].id == _id && voterlist[i].E_id == _E_id) { voterlist[i].blacklisted_by_admin = true; } } // Call the event emit trigger_event(); } // Add users(Voters), but first add Admin // Remember user_count is same as id function add_user( address _add, string memory _name, string memory _email, string memory _pwd, int256 _permissions ) public { user_count++; users[user_count].id = user_count; users[user_count].add = _add; users[user_count].name = _name; users[user_count].email = _email; users[user_count].cand_index = 5000; users[user_count].permissions = _permissions; addresses[_add] = user_count; users[user_count].pwd = _pwd; // Call the event emit trigger_event(); } uint256 public candidate_count = 0; uint256 i = 0; uint256 j = 0; // user has applied for the candidature in a particular election function add_candidate( uint256 _C_id, string memory _C_name, uint256 _E_id, string memory _C_info ) public { // Require that the user is not an Admin require(users[_C_id].id != 1, "The User is not an Admin"); require( users[_C_id].cand_index == 5000, "Require the candidate was not an approved candidate previously" ); uint256 cflag = 0; //Require that user was voter for that particular election as well for (i = 1; i <= voter_list_count; i++) { if ((voterlist[i].id == _C_id) && (voterlist[i].E_id == _E_id)) { cflag = 1; break; } } require( cflag == 1, "require that user is voter in same election initially" ); cflag = 0; for (i = 1; i <= voter_list_count; i++) { if ( (voterlist[i].id == _C_id) && (voterlist[i].E_id == _E_id) && (voterlist[i].blacklisted_by_admin != true) ) { cflag = 1; break; } } require(cflag == 1, "require that user not reported for this election"); cflag = 0; //check if the candidate has not applied previously for this election; for (i = 0; i < candidate_count; i++) { if (candidates[i].C_id == _C_id && candidates[i].E_id == _E_id) { cflag = 1; } } require( cflag == 0, "Candidate should not have applied previously for this election" ); // Check if we can change the user struct value candidates.push( candidate({ C_id: _C_id, vote_count: 0, C_name: _C_name, E_id: _E_id, C_info: _C_info, deleted: false }) ); candidate_count++; // Call the event emit trigger_event(); } //approves candidature after candidate applies for the election function candidate_approved_by_admin(uint256 _C_id) public { require( users[_C_id].permissions == 0, "Require the candidate was not an approved candidate previously" ); users[_C_id].permissions = 1; uint256 i = 0; for (; i < candidate_count; i++) { if (candidates[i].C_id == _C_id) { users[_C_id].cand_index = i; break; } } // Call the event emit trigger_event(); } function add_voter_by_admin(uint256 _E_id, uint256 _id) public { voter_list_count++; voterlist[voter_list_count].E_id = _E_id; voterlist[voter_list_count].id = _id; voterlist[voter_list_count].voted = false; voterlist[voter_list_count].reportedByUser = false; voterlist[voter_list_count].blacklisted_by_admin = false; // Call the event emit trigger_event(); } // JS will always call delete, and delete depending on the // type of delete // type 0: Eletion, 1: Voter, 2: Candidate // For Delete eletion, id will be 0 function admin_delete( uint256 _id, uint256 _E_id, uint256 _type ) public { uint256 i; require(_E_id > 0, "Eletion IDs are always positive"); require( _E_id <= election_count, "Eletion IDs are always less than or equal to election_count" ); // Delete Election if (_type == 0) { elections[_E_id].deleted = true; } // Delete Voter else if (_type == 1) { require(_id > 1, "User ID should be greater than 1(admin)"); require( _id <= user_count, "User ID should be less than or equal to user_count" ); for (i = 1; i <= voter_list_count; i++) { if (voterlist[i].E_id == _E_id && voterlist[i].id == _id) { voterlist[i].deleted = true; } } } // Delete Candidate else if (_type == 2) { require(_id > 1, "User ID should be greater than 1(admin)"); require( _id <= user_count, "User ID should be less than or equal to user_count" ); uint256 _cand_index = users[_id].cand_index; require( _cand_index < 5000, "The user should be an already registerd candidate" ); candidates[_cand_index].deleted = true; } // Call the event emit trigger_event(); } // function delete_voter_by_admin(uint256 _voter_index) public{ // voterlist[_voter_index].deleted = true; // // Call the event // emit trigger_event() // } function vote( uint256 _C_id, uint256 _E_id, uint256 _id ) public { // Require that the user is not the admin require(users[1].add != msg.sender, "The User is not an Admin"); // Require that the _C_id is present in the candidates list require( users[_C_id].permissions == 1, "Candidate is a part of candidate list" ); //Election id of candidate and voter are same // Require to check that the voter hasn't voted before for (i = 1; i <= voter_list_count; i++) { if (voterlist[i].id == _id && voterlist[i].E_id == _E_id) { require(!voterlist[i].voted, "The voter hasn't voted before"); voterlist[i].voted = true; break; } } for (j = 0; j < candidate_count; j++) { if (candidates[j].C_id == _C_id) { candidates[j].vote_count++; } } // trigger voted event // emit votedEvent(_C_id); // Call the event emit trigger_event(); } function uploadCampaign(string memory _desc, uint256 _E_id) public { // Make sure the image hash exists require(bytes(_desc).length > 0); // Make sure image description exists //require(bytes(_description).length > 0); // Make sure uploader address exists require(msg.sender != address(0)); //Increment campaign count campaign_count++; uint256 i = 0; uint256 u_id; uint256 e_id; string memory name; uint256 cnd_index; for (i = 2; i <= user_count; i++) { if (users[i].add == msg.sender) { u_id = users[i].id; name = users[i].name; cnd_index = users[i].cand_index; break; } } //that user is a candidate in the election e_id = candidates[cnd_index].E_id; require(e_id == _E_id); //Add image to contract //passing fifth argument 1 as of now, needs to be changed campaigns[campaign_count] = campaign( campaign_count, _desc, u_id, e_id, name ); // Call the event emit trigger_event(); } // Constructor constructor() public { // Add admin first //Rhugaved // add_user( // 0x22e9140a50BdB2659b9E473dAa645685C4f409E5, // "admin", // "[email protected]", // "123", // 2 // ); // add_user( // 0x1BFf1D5FF4234912Efc5fE4FE6Fe8038366A30E1, // "voter 1", // "[email protected]", // "123", // 0 // ); // add_user( // 0xCD56ad160221d01ea132F05D4057665A97C6934D, // "voter 2", // "[email protected]", // "123", // 0 // ); // add_user( // 0x2D89b40E5C820Ee508577ac851DF5e1Bb095C037, // "cand 1", // "[email protected]", // "123", // 0 // ); // add_user( // 0x6f7B8dF18264EeF57c112a94ce06cc2fa705ab71, // "cand 2", // "[email protected]", // "123", // 0 // ); // add_user( // 0x33fF69744215B3E8b8389D70C2A358BFB3fA16ae, // "Reported", // "[email protected]", // "123", // 0 // ); //himansh add_user( 0xCBAD3fB515C349Bfee52b12AfCc75B90Ce93d61F, "admin", "[email protected]", "123", 2 ); // add_user( // 0x347498952f9a102aAf611d66b4A9eb1c822AcF5A, // "voter 1", // "[email protected]", // "123", // 0 // ); // add_user( // 0x108dd6Db4E153BcE120bf8EF9E1473f32dea9248, // "voter 2", // "[email protected]", // "123", // 0 // ); // add_user( // 0x43e25608d87fE3faA8686Ac89A4Fe98d57A4b3cb, // "cand 1", // "[email protected]", // "123", // 0 // ); // add_user( // 0x2c2E70D6c73B51D84B0eD7BF52994A6C74Fe74aB, // "cand 2", // "[email protected]", // "123", // 0 // ); //muskan // add_user( // 0x7D8d4E73350E695e351E80705B8B6F30bAcF00CC, // "admin", // "[email protected]", // "123", // 2 // ); // add_user( // 0x2aeE3162bB87A4Ed18eE0abB27f6d2CE3F5A6720, // "voter 1", // "[email protected]", // "123", // 0 // ); // add_user( // 0x145d98eBca32EC5C25e49D76D95cEc2E4cA2852E, // "voter 2", // "[email protected]", // "123", // 0 // ); // add_user( // 0x7F5542Cd4C3f34ad08747273E42CB8855eDD23d4, // "cand 1", // "[email protected]", // "123", // 0 // ); // add_user( // 0x339531797eBa4492570C40Cc40dfee612dd9540F, // "cand 2", // "[email protected]", // "123", // 0 // ); // add_user( // 0x12a79A0f247F3912e45A8B3EdAec0fdD46C5C660, // "Reported", // "[email protected]", // "123", // 0 // ); // add_voter_by_admin(1, 2); // add_voter_by_admin(1, 3); // add_voter_by_admin(2, 3); // add_election("Gykhana", 5000, 1618926000, 1618940000); // add_election("Sec", 5000, 6000, 7000); // add_candidate(3, "candidate 1", 1); // add_candidate(2, "voter 1", 1); // candidate_approved_by_admin(2); // candidate_approved_by_admin(3); // report_by_user(2, 1, "Fake"); } }
that user is a candidate in the election
e_id = candidates[cnd_index].E_id;
12,717,984
[ 1, 19056, 729, 353, 279, 5500, 316, 326, 25526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 425, 67, 350, 273, 7965, 63, 71, 4880, 67, 1615, 8009, 41, 67, 350, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; import "./libraries/SafeMath.sol"; import "./Oraclize/Oraclize_API.sol"; import "./Wrapped_Token.sol"; import "./libraries/Strings.sol"; /** *Side chain bridge contract */ /** * This is the basic wrapped Ether to a different chain contract. * All money deposited is transformed into ERC20 tokens at the rate of 1 wei = 1 token * You push money when you transfer (delete money here). If it doesn't go through, * you can check to see if transfer ID went through */ contract DappBridge is usingOraclize, Wrapped_Token{ using SafeMath for uint256; /***Variables***/ string public bridgedChain; uint transNonce; string public partnerBridge; //address of bridge contract on other chain string api; string parameters; address public owner; bytes4 method_data; uint public public_fund; struct Details{ uint amount; address owner; uint transferId; } /***Storage**/ mapping(uint => Details) transferDetails; //maps a transferId to an amount mapping(address => uint[]) transferList; //list of all transfers from an address; mapping(uint => bool) pulledTransaction; /***Events***/ event Locked(uint _id,address _from, uint _value); event LogUpdated(string value); event LogNewOraclizeQuery(string description); /***Functions***/ constructor() public { owner = msg.sender; } //enter your custom OAR here: function setOAR(address _oar) public onlyOwner() { OAR = OraclizeAddrResolverI(_oar); } /***Modifiers***/ /** * @dev Access modifier for Owner functionality */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the owner to set a new owner address * @param _owner the new owner address */ function setOwner (address _owner) public onlyOwner(){ owner = _owner; } /** * @dev Locks side chain tokens and returns the transactionID/transNonce used in the * Bridge.CheckChild function. It also destroys the sidechain tokens that represented * the originally transferred Ether. * @param _amount The amount of tokens to lock */ function lockForTransfer(uint _amount) public returns(uint){ transNonce += 1; require (balances[msg.sender] >= _amount && _amount > 0); balances[msg.sender] = balances[msg.sender].sub(_amount); total_supply = total_supply.sub(_amount); transferDetails[transNonce] = Details({ amount:_amount, owner:msg.sender, transferId:transNonce }); transferList[msg.sender].push(transNonce); emit Locked(transNonce,msg.sender,_amount); return(transNonce); } /** * @dev Checks main chain for Ether is locked for tranfer through their transferId. * @param _id from locked Ether on the main chain. It includes the string * of parameters including the bytes4 code address of the getTransfer fuction on the * mainchain to get the tranfer details (amount, owner, transferId) * TO DO: We need to append address to end of data_string */ function checkMain(uint _id) public payable{ if (oraclize_getPrice("URL") * 2 > msg.value) { emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogNewOraclizeQuery("Oraclize query was sent for locked balance"); string memory _params = createQuery_value(_id); oraclize_query("URL",api,_params, 3000000); } } /** * @dev This function is called from the main chain through its 4-byte code * address through the oraclize function within the CheckChild function in the main chain */ function getTransfer(uint _transferId) public view returns(uint,address,uint){ Details memory _locked = transferDetails[_transferId]; return(_locked.amount,_locked.owner,_locked.transferId); } /** * @dev creates a string needed for the oraclize query * @param u_id is the transactionId obtained from the DappBridge.CheckMain._id * which is the same as the same as the Bridge.lockforTransfer return(transNonce) * TO DO: can make internal once it works * TO DO:check id (60 is an open, so we can try it) */ function createQuery_value(uint u_id) public constant returns(string){ bytes32 _s_id = bytes32(u_id); string memory _id = Strings.fromB32(_s_id); string memory _code = strConcat(partnerBridge,',"data":"',Strings.fromCode(method_data),_id,'"},"latest"]}'); string memory _params2 = strConcat(' {"jsonrpc":"2.0","id":60,"method":"eth_call","params":[{"to":',_code); return _params2; } /** * @dev Gets the oraclize query results as as string, parses the string to * get the amount, owner, transferID, updates the owner's/sender side chain * token balance * @param myid is the oraclize query ID * @param result is a string of the amount, owner, and transferId from the * Bridge.getTransfer function */ function __callback(bytes32 myid, string result) public{ require (msg.sender == oraclize_cbAddress()); uint startIdx = 0; if(Strings.hasZeroXPrefix(result)) { startIdx = 2; } bytes memory bts = bytes(result); //take the first 64 bytes and convert to uint uint _amount = Strings.hexToUint(Strings.substr(result, startIdx,64+startIdx)); //id is at the end and will be 64 bytes. So grab its starting idx first. uint idStart = bts.length - 64; //the address portion will end where the id starts. uint addrEnd = idStart; //parse the last 40 bytes of the address hex. address _owner = Strings.parseAddr(Strings.substr(result, addrEnd-40, addrEnd)); //then extract the id uint _transId = Strings.hexToUint(Strings.substr(result, idStart, bts.length)); require(pulledTransaction[_transId] == false); balances[_owner] = balances[_owner].add(_amount); total_supply = total_supply.add(_amount); pulledTransaction[_transId] = true; emit LogUpdated(result); if (public_fund > 1e17){ _owner.transfer(1e17); } } /** * @dev Set partner bridge contract address from the main chain * @param _connected is the Bridge cotnract address on main chain * and should be entered as string */ function setPartnerBridge(string _connected) public onlyOwner(){ partnerBridge = strConcat('"',_connected,'"'); method_data = this.getTransfer.selector; } /** * @dev Sets API for sidechain * @param _api for mide chain as string such as an Infura hosted node * try: //"json(https://ropsten.infura.io/).result" */ function setAPI(string _api) public onlyOwner(){ api = _api; //"json(https://ropsten.infura.io/).result" } function fund() public payable(){ } }
enter your custom OAR here:
function setOAR(address _oar) public onlyOwner() { OAR = OraclizeAddrResolverI(_oar); }
2,501,157
[ 1, 2328, 3433, 1679, 531, 985, 2674, 30, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 51, 985, 12, 2867, 389, 83, 297, 13, 1071, 1338, 5541, 1435, 288, 203, 3639, 531, 985, 273, 531, 354, 830, 554, 3178, 4301, 45, 24899, 83, 297, 1769, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/421613/0xD34d6f95A3C23Ce1A1c8F3130062CEeeE69d1148/sources/project_/contracts/LuckyWheel.sol
rand number with public state always changes
function spinWheel() external nonReentrant notContract { uint256 _available = user[msg.sender].balance; require(_available >= cost, "not enough to pay spin cost"); updateSeed(); uint256 result = 15; if(randomNumber <= 50000){ for (uint256 i = 0; i < chances.length; i++) { if (randomNumber <= chances[i]) { result = i; break; } } } uint256[] memory rewardList = calculateRewards(); user[msg.sender].winBalance = user[msg.sender].winBalance.add(rewardList[result]); totalWin = totalWin.add(rewardList[result]); rewardPools = rewardPools.add(cost); spinCount += 1; emit Wheels(msg.sender, result, rewardList[result], randomNumber); }
11,574,446
[ 1, 7884, 1300, 598, 1071, 919, 3712, 3478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12490, 59, 11648, 1435, 3903, 1661, 426, 8230, 970, 486, 8924, 288, 203, 3639, 2254, 5034, 389, 5699, 273, 729, 63, 3576, 18, 15330, 8009, 12296, 31, 203, 3639, 2583, 24899, 5699, 1545, 6991, 16, 315, 902, 7304, 358, 8843, 12490, 6991, 8863, 203, 203, 3639, 1089, 12702, 5621, 203, 3639, 2254, 5034, 563, 273, 4711, 31, 203, 3639, 309, 12, 9188, 1854, 1648, 1381, 2787, 15329, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3861, 764, 18, 2469, 31, 277, 27245, 288, 203, 7734, 309, 261, 9188, 1854, 1648, 3861, 764, 63, 77, 5717, 288, 203, 10792, 563, 273, 277, 31, 203, 10792, 898, 31, 203, 7734, 289, 203, 5411, 289, 2868, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 8526, 3778, 19890, 682, 273, 4604, 17631, 14727, 5621, 203, 3639, 729, 63, 3576, 18, 15330, 8009, 8082, 13937, 273, 729, 63, 3576, 18, 15330, 8009, 8082, 13937, 18, 1289, 12, 266, 2913, 682, 63, 2088, 19226, 203, 3639, 2078, 18049, 273, 2078, 18049, 18, 1289, 12, 266, 2913, 682, 63, 2088, 19226, 203, 3639, 19890, 16639, 273, 19890, 16639, 18, 1289, 12, 12398, 1769, 7010, 3639, 12490, 1380, 1011, 404, 31, 21281, 203, 3639, 3626, 678, 580, 10558, 12, 3576, 18, 15330, 16, 563, 16, 19890, 682, 63, 2088, 6487, 2744, 1854, 1769, 4766, 17311, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BlueOak-1.0.0 // solhint-disable func-name-mixedcase func-visibility pragma solidity ^0.8.9; /// @title FixedPoint, a fixed-point arithmetic library defining the custom type uint192 /// @author Matt Elder <[email protected]> and the Reserve Team <https://reserve.org> /** The logical type `uint192 ` is a 192 bit value, representing an 18-decimal Fixed-point fractional value. This is what's described in the Solidity documentation as "fixed192x18" -- a value represented by 192 bits, that makes 18 digits available to the right of the decimal point. The range of values that uint192 can represent is about [-1.7e20, 1.7e20]. Unless a function explicitly says otherwise, it will fail on overflow. To be clear, the following should hold: toFix(0) == 0 toFix(1) == 1e18 */ // A uint value passed to this library was out of bounds for uint192 operations error UIntOutOfBounds(); // Used by P1 implementation for easier casting uint256 constant FIX_ONE_256 = 1e18; uint8 constant FIX_DECIMALS = 18; // If a particular uint192 is represented by the uint192 n, then the uint192 represents the // value n/FIX_SCALE. uint64 constant FIX_SCALE = 1e18; // FIX_SCALE Squared: uint128 constant FIX_SCALE_SQ = 1e36; // The largest integer that can be converted to uint192 . // This is a bit bigger than 3.1e39 uint192 constant FIX_MAX_INT = type(uint192).max / FIX_SCALE; uint192 constant FIX_ZERO = 0; // The uint192 representation of zero. uint192 constant FIX_ONE = FIX_SCALE; // The uint192 representation of one. uint192 constant FIX_MAX = type(uint192).max; // The largest uint192. (Not an integer!) uint192 constant FIX_MIN = 0; // The smallest uint192. /// An enum that describes a rounding approach for converting to ints enum RoundingMode { FLOOR, // Round towards zero ROUND, // Round to the nearest int CEIL // Round away from zero } RoundingMode constant FLOOR = RoundingMode.FLOOR; RoundingMode constant ROUND = RoundingMode.ROUND; RoundingMode constant CEIL = RoundingMode.CEIL; /* @dev Solidity 0.8.x only allows you to change one of type or size per type conversion. Thus, all the tedious-looking double conversions like uint256(uint256 (foo)) See: https://docs.soliditylang.org/en/v0.8.9/080-breaking-changes.html#new-restrictions */ /// Explicitly convert a uint256 to a uint192. Revert if the input is out of bounds. function _safeWrap(uint256 x) pure returns (uint192) { if (FIX_MAX < x) revert UIntOutOfBounds(); return uint192(x); } /// Convert a uint to its uint192 representation. Fails if x is outside uint192's representable range. function toFix(uint256 x) pure returns (uint192) { return _safeWrap(x * FIX_SCALE); } /// Convert a uint to its fixed-point representation after left-shifting its value `shiftLeft` /// decimal digits. Fails if the result is outside uint192's representable range. function shiftl_toFix(uint256 x, int8 shiftLeft) pure returns (uint192) { return shiftl_toFix(x, shiftLeft, FLOOR); } function shiftl_toFix( uint256 x, int8 shiftLeft, RoundingMode rounding ) pure returns (uint192) { shiftLeft += 18; if (x == 0 || shiftLeft < -77) return 0; // shift would clear a uint256; 0 -> 0 if (77 < shiftLeft) revert UIntOutOfBounds(); // would unconditionally overflow x uint256 coeff = 10**abs(shiftLeft); uint256 shifted = (shiftLeft >= 0) ? x * coeff : _divrnd(x, coeff, rounding); return _safeWrap(shifted); } /// Divide a uint by a uint192 . Fails if the result is outside uint192's representable range /// (May also fail if the result is MIN_uint192 ; not fixing this for optimization's sake.) function divFix(uint256 x, uint192 y) pure returns (uint192) { // If we didn't have to worry about overflow, we'd just do `return x * 1e36 / _y` // If it's safe to do this operation the easy way, do it: if (x < uint256(type(uint256).max / FIX_SCALE_SQ)) { return _safeWrap(uint256(x * FIX_SCALE_SQ) / y); } else { return _safeWrap(mulDiv256(x, FIX_SCALE_SQ, y)); } } /// Divide a uint by a uint, yielding a fix function divuu(uint256 x, uint256 y) pure returns (uint192) { return _safeWrap(mulDiv256(FIX_SCALE, x, y)); } function fixMin(uint192 x, uint192 y) pure returns (uint192) { return x < y ? x : y; } function fixMax(uint192 x, uint192 y) pure returns (uint192) { return x > y ? x : y; } function abs(int256 x) pure returns (uint256) { return x < 0 ? uint256(-x) : uint256(x); } /// internal: Do an internal division with given rounding. Where numerator and divisor are uint200s /// (not presumed to be fixed-point values!), return numerator/divisor. /// Round the division's result as specified by `rounding`. function _divrnd( uint256 numerator, uint256 divisor, RoundingMode rounding ) pure returns (uint256) { uint256 result = numerator / divisor; if (rounding == FLOOR) return result; if (rounding == ROUND) { if (numerator % divisor > (divisor - 1) / 2) { result++; } } else { if (numerator % divisor > 0) { result++; } } return result; } library FixLib { /// All arithmetic functions fail if and only if the result is out of bounds. /// Convert this fixed-point value to a uint; round the result towards zero function toUint(uint192 x) internal pure returns (uint136) { return toUint(x, FLOOR); } /// Convert this uint192 to a uint, applying the rounding approach described by the enum function toUint(uint192 x, RoundingMode rounding) internal pure returns (uint136) { return uint136(_divrnd(uint256(x), FIX_SCALE, rounding)); } /// Return the uint192 shifted to the left by `decimal` digits /// Similar to a bitshift but in base 10 /// Equivalent to multiplying `x` by `10**decimal` function shiftl(uint192 x, int8 decimals) internal pure returns (uint192) { return shiftl(x, decimals, FLOOR); } /// Return the uint192 shifted to the left by `decimal` digits /// (Similar to a bitshift but in base 10) /// Equivalent to multiplying `x` by `10**decimal` function shiftl( uint192 x, int8 decimals, RoundingMode rounding ) internal pure returns (uint192) { uint256 coeff = uint256(10**abs(decimals)); return _safeWrap(decimals >= 0 ? x * coeff : _divrnd(x, coeff, rounding)); } /// Add a uint192 to this uint192 . function plus(uint192 x, uint192 y) internal pure returns (uint192) { return x + y; } /// Add a uint to this uint192 . function plusu(uint192 x, uint256 y) internal pure returns (uint192) { return _safeWrap(x + y * FIX_SCALE); } /// Subtract a uint192 from this uint192 . function minus(uint192 x, uint192 y) internal pure returns (uint192) { return x - y; } /// Subtract a uint from this uint192 . function minusu(uint192 x, uint256 y) internal pure returns (uint192) { return _safeWrap(uint256(x) - uint256(y * FIX_SCALE)); } /// Multiply this uint192 by a uint192 . /// Round truncated values to the nearest available value. 5e-19 rounds away from zero. function mul(uint192 x, uint192 y) internal pure returns (uint192) { return mul(x, y, ROUND); } function mul( uint192 x, uint192 y, RoundingMode rounding ) internal pure returns (uint192) { return _safeWrap(_divrnd(uint256(x) * uint256(y), FIX_SCALE, rounding)); } /// Multiply this uint192 by a uint. function mulu(uint192 x, uint256 y) internal pure returns (uint192) { return _safeWrap(x * y); } /// Divide this uint192 by a uint192 ; round the fractional part towards zero. function div(uint192 x, uint192 y) internal pure returns (uint192) { return div(x, y, FLOOR); } function div( uint192 x, uint192 y, RoundingMode rounding ) internal pure returns (uint192) { // Multiply-in FIX_SCALE before dividing by y to preserve precision. return _safeWrap(_divrnd(uint256(x) * FIX_SCALE, y, rounding)); } /// Divide this uint192 by a uint. function divu(uint192 x, uint256 y) internal pure returns (uint192) { return divu(x, y, FLOOR); } function divu( uint192 x, uint256 y, RoundingMode rounding ) internal pure returns (uint192) { return _safeWrap(_divrnd(x, y, rounding)); } uint64 constant FIX_HALF = uint64(FIX_SCALE) / 2; /// Raise this uint192 to a nonnegative integer power. /// Presumes that powu(0.0, 0) = 1 /// @dev The gas cost is O(lg(y)) /// Intermediate muls do nearest-value rounding. function powu(uint192 x_, uint32 y) internal pure returns (uint192) { // The algorithm is exponentiation by squaring. See: https://w.wiki/4LjE if (y == 1) return x_; if (x_ == FIX_ONE || y == 0) return FIX_ONE; uint256 x = uint256(x_); uint256 result = FIX_SCALE; while (true) { if (y & 1 == 1) result = (result * x + FIX_HALF) / FIX_SCALE; if (y <= 1) break; y = y >> 1; x = (x * x + FIX_HALF) / FIX_SCALE; } return _safeWrap(result); } /// Comparison operators... function lt(uint192 x, uint192 y) internal pure returns (bool) { return x < y; } function lte(uint192 x, uint192 y) internal pure returns (bool) { return x <= y; } function gt(uint192 x, uint192 y) internal pure returns (bool) { return x > y; } function gte(uint192 x, uint192 y) internal pure returns (bool) { return x >= y; } function eq(uint192 x, uint192 y) internal pure returns (bool) { return x == y; } function neq(uint192 x, uint192 y) internal pure returns (bool) { return x != y; } /// Return whether or not this uint192 is less than epsilon away from y. function near( uint192 x, uint192 y, uint192 epsilon ) internal pure returns (bool) { uint192 diff = x <= y ? y - x : x - y; return diff < epsilon; } // ================ Chained Operations ================ // The operation foo_bar() always means: // Do foo() followed by bar(), and overflow only if the _end_ result doesn't fit in an uint192 function shiftl_toUint(uint192 x, int8 decimals) internal pure returns (uint256) { return shiftl_toUint(x, decimals, FLOOR); } /// Shift this uint192 , left by `decimals`, and then convert the result to a uint. /// Do all this applying the given rounding mode. /// Overflow only if the end result doesn't fit in an uint192 . function shiftl_toUint( uint192 x, int8 decimals, RoundingMode rounding ) internal pure returns (uint256) { decimals -= 18; // shift so that toUint happens at the same time. uint256 coeff = uint256(10**abs(decimals)); return decimals >= 0 ? uint256(x * coeff) : uint256(_divrnd(x, coeff, rounding)); } /// Multiply this uint192 by a uint and output the result as a uint, rounding towards zero. function mulu_toUint(uint192 x, uint256 y) internal pure returns (uint256) { return mulDiv256(uint256(x), y, FIX_SCALE); } /// Multiply this uint192 by a uint and output the result as a uint, rounding as specified. function mulu_toUint( uint192 x, uint256 y, RoundingMode rounding ) internal pure returns (uint256) { return mulDiv256(uint256(x), y, FIX_SCALE, rounding); } /// Multiply this uint192 by a uint192 and output the result as a uint, rounding towards zero. function mul_toUint(uint192 x, uint192 y) internal pure returns (uint256) { return mulDiv256(uint256(x), uint256(y), FIX_SCALE_SQ); } /// Multiply this uint192 by a uint192 and output the result as a uint, rounding towards zero. function mul_toUint( uint192 x, uint192 y, RoundingMode rounding ) internal pure returns (uint256) { return mulDiv256(uint256(x), uint256(y), FIX_SCALE_SQ, rounding); } /// A chained .mul + .div on uints that avoids intermediate overflow /// @dev Do not use if you don't need it; has higher gas costs than x * y / z function muluDivu( uint192 x, uint256 y, uint256 z ) internal pure returns (uint192) { return muluDivu(x, y, z, FLOOR); } /// A chained .mul + .div on uints that avoids intermediate overflow /// @dev Do not use if you don't need it; has higher gas costs than x * y / z function muluDivu( uint192 x, uint256 y, uint256 z, RoundingMode rounding ) internal pure returns (uint192) { return _safeWrap(mulDiv256(x, y, z, rounding)); } /// A chained .mul + .div on Fixes that avoids intermediate overflow /// @dev Do not use if you don't need it; has higher gas costs than x * y / z function mulDiv( uint192 x, uint192 y, uint192 z ) internal pure returns (uint192) { return mulDiv(x, y, z, FLOOR); } /// A chained .mul + .div on Fixes that avoids intermediate overflow /// @dev Do not use if you don't need it; has higher gas costs than x * y / z function mulDiv( uint192 x, uint192 y, uint192 z, RoundingMode rounding ) internal pure returns (uint192) { return _safeWrap(mulDiv256(x, y, z, rounding)); } } // ================ a couple pure-uint helpers================ /// mulDiv: return (x*y/z), overflowing *only* if the end result is out of range. /// Adapted from sources: /// https://medium.com/coinmonks/4db014e080b1, https://medium.com/wicketh/afa55870a65 /// and quite a few of the other excellent "Mathemagic" posts from https://medium.com/wicketh /// @dev Just use x*y/z unless you need to avoid intermediate overflow. This has higher gas costs function mulDiv256( uint256 x, uint256 y, uint256 z ) pure returns (uint256 result) { unchecked { (uint256 lo, uint256 hi) = fullMul(x, y); if (hi >= z) revert UIntOutOfBounds(); uint256 mm = mulmod(x, y, z); if (mm > lo) hi -= 1; lo -= mm; uint256 pow2 = z & (0 - z); z /= pow2; lo /= pow2; lo += hi * ((0 - pow2) / pow2 + 1); uint256 r = 1; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; result = lo * r; } } /// return (x*y/z), overflowing only if the end result is out of range, and having the division /// round as specified by `rounding`. function mulDiv256( uint256 x, uint256 y, uint256 z, RoundingMode rounding ) pure returns (uint256) { uint256 result = mulDiv256(x, y, z); if (rounding == FLOOR) return result; uint256 mm = mulmod(x, y, z); if (rounding == CEIL) { if (mm > 0) result += 1; } else { if (mm > ((z - 1) / 2)) result += 1; // z should be z-1 } return result; } /// fullMul: return (x*y) as a "virtual uint512" /// The computed result is (hi*2^256 + lo) /// Adapted from sources: /// https://medium.com/wicketh/27650fec525d, https://medium.com/coinmonks/4db014e080b1 /// @dev Intended to be internal to this library function fullMul(uint256 x, uint256 y) pure returns (uint256 lo, uint256 hi) { unchecked { uint256 mm = mulmod(x, y, uint256(0) - uint256(1)); lo = x * y; hi = mm - lo; if (mm < lo) hi -= 1; } }
Raise this uint192 to a nonnegative integer power. Presumes that powu(0.0, 0) = 1 @dev The gas cost is O(lg(y)) Intermediate muls do nearest-value rounding. The algorithm is exponentiation by squaring. See: https:w.wiki/4LjE
function powu(uint192 x_, uint32 y) internal pure returns (uint192) { if (y == 1) return x_; if (x_ == FIX_ONE || y == 0) return FIX_ONE; uint256 x = uint256(x_); uint256 result = FIX_SCALE; while (true) { if (y & 1 == 1) result = (result * x + FIX_HALF) / FIX_SCALE; if (y <= 1) break; y = y >> 1; x = (x * x + FIX_HALF) / FIX_SCALE; } return _safeWrap(result); }
12,832,621
[ 1, 30570, 333, 2254, 15561, 358, 279, 1661, 13258, 3571, 7212, 18, 18346, 6411, 716, 7602, 89, 12, 20, 18, 20, 16, 374, 13, 273, 404, 225, 1021, 16189, 6991, 353, 531, 12, 23623, 12, 93, 3719, 5294, 6785, 14064, 87, 741, 11431, 17, 1132, 13885, 18, 1021, 4886, 353, 9100, 7072, 635, 17715, 5968, 18, 2164, 30, 2333, 30, 91, 18, 13044, 19, 24, 48, 78, 41, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7602, 89, 12, 11890, 15561, 619, 67, 16, 2254, 1578, 677, 13, 2713, 16618, 1135, 261, 11890, 15561, 13, 288, 203, 3639, 309, 261, 93, 422, 404, 13, 327, 619, 67, 31, 203, 3639, 309, 261, 92, 67, 422, 8563, 67, 5998, 747, 677, 422, 374, 13, 327, 8563, 67, 5998, 31, 203, 3639, 2254, 5034, 619, 273, 2254, 5034, 12, 92, 67, 1769, 203, 3639, 2254, 5034, 563, 273, 8563, 67, 19378, 31, 203, 3639, 1323, 261, 3767, 13, 288, 203, 5411, 309, 261, 93, 473, 404, 422, 404, 13, 563, 273, 261, 2088, 380, 619, 397, 8563, 67, 44, 21497, 13, 342, 8563, 67, 19378, 31, 203, 5411, 309, 261, 93, 1648, 404, 13, 898, 31, 203, 5411, 677, 273, 677, 1671, 404, 31, 203, 5411, 619, 273, 261, 92, 380, 619, 397, 8563, 67, 44, 21497, 13, 342, 8563, 67, 19378, 31, 203, 3639, 289, 203, 3639, 327, 389, 4626, 2964, 12, 2088, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xaEAD18A6f788fb7460aDA9fDFf4C4Cd6Ba72dDBE/sources/contracts/ERC2981Royalties.sol
@dev This is a contract used to add ERC2981 support to ERC721 and 1155 @dev This implementation has the same royalties for each and every tokens
abstract contract ERC2981Royalties is ERC2981Base { RoyaltyInfo private _contractRoyalties; mapping(uint256 => RoyaltyInfo) private _individualRoyalties; pragma solidity ^0.8.0; function setTokenRoyalty(uint256 tokenId, address recipient, uint256 value) public override { require(msg.sender == OwnableUpgradeable(address(this)).owner(), "Not Owner"); require(value <= 10000, 'ERC2981Royalties: Too high'); if (tokenId == 0) { _contractRoyalties = RoyaltyInfo(recipient, uint24(value)); _individualRoyalties[tokenId] = RoyaltyInfo(recipient, uint24(value)); } } function setTokenRoyalty(uint256 tokenId, address recipient, uint256 value) public override { require(msg.sender == OwnableUpgradeable(address(this)).owner(), "Not Owner"); require(value <= 10000, 'ERC2981Royalties: Too high'); if (tokenId == 0) { _contractRoyalties = RoyaltyInfo(recipient, uint24(value)); _individualRoyalties[tokenId] = RoyaltyInfo(recipient, uint24(value)); } } } else { function royaltyInfo(uint256 tokenId, uint256 value) public view override returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo memory royalties = _individualRoyalties[tokenId].recipient != address(0)? _individualRoyalties[tokenId]: _contractRoyalties; receiver = royalties.recipient; royaltyAmount = (value * royalties.amount) / 10000; } }
4,998,912
[ 1, 2503, 353, 279, 6835, 1399, 358, 527, 4232, 39, 5540, 11861, 2865, 358, 4232, 39, 27, 5340, 471, 4648, 2539, 225, 1220, 4471, 711, 326, 1967, 721, 93, 2390, 606, 364, 1517, 471, 3614, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 5540, 11861, 54, 13372, 2390, 606, 353, 4232, 39, 5540, 11861, 2171, 288, 203, 565, 534, 13372, 15006, 966, 3238, 389, 16351, 54, 13372, 2390, 606, 31, 203, 565, 2874, 12, 11890, 5034, 516, 534, 13372, 15006, 966, 13, 3238, 389, 22032, 5557, 54, 13372, 2390, 606, 31, 203, 203, 377, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 22629, 54, 13372, 15006, 12, 11890, 5034, 1147, 548, 16, 1758, 8027, 16, 2254, 5034, 460, 13, 1071, 3849, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 14223, 6914, 10784, 429, 12, 2867, 12, 2211, 13, 2934, 8443, 9334, 315, 1248, 16837, 8863, 203, 3639, 2583, 12, 1132, 1648, 12619, 16, 296, 654, 39, 5540, 11861, 54, 13372, 2390, 606, 30, 15869, 3551, 8284, 203, 3639, 309, 261, 2316, 548, 422, 374, 13, 288, 203, 5411, 389, 16351, 54, 13372, 2390, 606, 273, 534, 13372, 15006, 966, 12, 20367, 16, 2254, 3247, 12, 1132, 10019, 203, 5411, 389, 22032, 5557, 54, 13372, 2390, 606, 63, 2316, 548, 65, 273, 534, 13372, 15006, 966, 12, 20367, 16, 2254, 3247, 12, 1132, 10019, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 22629, 54, 13372, 15006, 12, 11890, 5034, 1147, 548, 16, 1758, 8027, 16, 2254, 5034, 460, 13, 1071, 3849, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 14223, 6914, 10784, 429, 12, 2867, 12, 2211, 13, 2934, 8443, 9334, 315, 1248, 16837, 8863, 203, 3639, 2583, 12, 1132, 1648, 12619, 16, 2 ]
./partial_match/1/0x8Fbc2bD0F023c282EB6913444f26Ec8EC73DE967/sources/src/utils/Exp64x64.sol
SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.15; /*
4,162,780
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 4948, 48, 17, 23, 18, 20, 17, 280, 17, 29082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 3600, 31, 1748, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.8; import "./openzeppelin-contracts/math/SafeMath.sol"; import "./openzeppelin-contracts/introspection/IERC1820Registry.sol"; import "./openzeppelin-contracts/token/ERC777/IERC777.sol"; library Utils { using SafeMath for uint256; IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777Token") bytes32 constant private TOKENS_ERC777_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; function getTokenInfo(address tokenToUse) external view returns (uint8 decimals, uint256 granularity, string memory symbol) { decimals = getDecimals(tokenToUse); granularity = getGranularity(tokenToUse); symbol = getSymbol(tokenToUse); } function getSymbol(address tokenToUse) public view returns (string memory symbol) { //support 32 bytes or string symbol (bool success, bytes memory data) = tokenToUse.staticcall(abi.encodeWithSignature("symbol()")); require(success); if (data.length == 32) { symbol = bytes32ToString(abi.decode(data, (bytes32))); } else { symbol = abi.decode(data, (string)); } require(bytes(symbol).length > 0); return symbol; } function getDecimals(address tokenToUse) public view returns (uint8) { //support decimals as uint256 or uint8 (bool success, bytes memory data) = tokenToUse.staticcall(abi.encodeWithSignature("decimals()")); require(success); require(data.length == 32); // uint<M>: enc(X) is the big-endian encoding of X, //padded on the higher-order (left) side with zero-bytes such that the length is 32 bytes. uint256 decimalsDecoded = abi.decode(data, (uint256)); require(decimalsDecoded <= 18); return uint8(decimalsDecoded); } function getGranularity(address tokenToUse) public view returns (uint256 granularity) { granularity = 1; //support granularity if ERC777 address implementer = _erc1820.getInterfaceImplementer(tokenToUse, TOKENS_ERC777_HASH); if (implementer != address(0)) { granularity = IERC777(implementer).granularity(); //Verify granularity is power of 10 to keep it compatible with ERC20 decimals granularityToDecimals(granularity); } return granularity; } /* bytes32 (fixed-size array) to string (dynamically-sized array) */ function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function decimalsToGranularity(uint8 decimals) public pure returns (uint256) { require(decimals <= 18); return uint256(10)**(18-decimals); } function granularityToDecimals(uint256 granularity) public pure returns (uint8) { if(granularity == 1) return 18; if(granularity == 10) return 17; if(granularity == 100) return 16; if(granularity == 1000) return 15; if(granularity == 10000) return 14; if(granularity == 100000) return 13; if(granularity == 1000000) return 12; if(granularity == 10000000) return 11; if(granularity == 100000000) return 10; if(granularity == 1000000000) return 9; if(granularity == 10000000000) return 8; if(granularity == 100000000000) return 7; if(granularity == 1000000000000) return 6; if(granularity == 10000000000000) return 5; if(granularity == 100000000000000) return 4; if(granularity == 1000000000000000) return 3; if(granularity == 10000000000000000) return 2; if(granularity == 100000000000000000) return 1; if(granularity == 1000000000000000000) return 0; require(false); } function calculateGranularityAndAmount(uint8 decimals, uint256 granularity, uint256 amount) external pure returns(uint256 calculatedGranularity, uint256 formattedAmount) { if(decimals == 18) { //tokenAddress is a ERC20 with 18 decimals should have 1 granularity //tokenAddress is a ERC777 token we give the same granularity calculatedGranularity = granularity; formattedAmount = amount; } else { //tokenAddress is a ERC20 with other than 18 decimals calculatedGranularity = decimalsToGranularity(decimals); formattedAmount = amount.mul(calculatedGranularity); } } function calculateDecimalsAndAmount(address tokenAddress, uint256 granularity, uint256 amount) external view returns (uint8 calculatedDecimals, uint256 formattedAmount) { uint8 tokenDecimals = getDecimals(tokenAddress); //As side tokens are ERC777 we need to convert granularity to decimals calculatedDecimals = granularityToDecimals(granularity); require(tokenDecimals == calculatedDecimals); formattedAmount = amount.div(granularity); } }
support decimals as uint256 or uint8 uint<M>: enc(X) is the big-endian encoding of X,padded on the higher-order (left) side with zero-bytes such that the length is 32 bytes.
function getDecimals(address tokenToUse) public view returns (uint8) { (bool success, bytes memory data) = tokenToUse.staticcall(abi.encodeWithSignature("decimals()")); require(success); require(data.length == 32); uint256 decimalsDecoded = abi.decode(data, (uint256)); require(decimalsDecoded <= 18); return uint8(decimalsDecoded); }
1,786,085
[ 1, 13261, 15105, 487, 2254, 5034, 578, 2254, 28, 2254, 32, 49, 28593, 2446, 12, 60, 13, 353, 326, 5446, 17, 22910, 2688, 434, 1139, 16, 6982, 785, 603, 326, 10478, 17, 1019, 261, 4482, 13, 4889, 598, 3634, 17, 3890, 4123, 716, 326, 769, 353, 3847, 1731, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 31809, 12, 2867, 1147, 18762, 13, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 501, 13, 273, 1147, 18762, 18, 3845, 1991, 12, 21457, 18, 3015, 1190, 5374, 2932, 31734, 1435, 7923, 1769, 203, 3639, 2583, 12, 4768, 1769, 203, 3639, 2583, 12, 892, 18, 2469, 422, 3847, 1769, 203, 3639, 2254, 5034, 15105, 24888, 273, 24126, 18, 3922, 12, 892, 16, 261, 11890, 5034, 10019, 203, 3639, 2583, 12, 31734, 24888, 1648, 6549, 1769, 203, 3639, 327, 2254, 28, 12, 31734, 24888, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x6842147BDC6ed968343A4DAcc035885e4804043b/sources/LiquidityPoolV1Converter.sol
* @dev Liquidity Pool v1 Converter The liquidity pool v1 converter is a specialized version of a converter that manages a classic bancor liquidity pool. Even though pools can have many reserves, the standard pool configuration is 2 reserves with 50%/50% weights./ the period of time taken into account when calculating the recent averate rate true if the pool is a 2 reserves / 50%/50% weights pool, false otherwise only used in standard pools
contract LiquidityPoolV1Converter is LiquidityPoolConverter { using Math for *; IEtherToken internal etherToken = IEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315); uint256 internal constant MAX_RATE_FACTOR_LOWER_BOUND = 1e30; uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes; bool public isStandardPool = false; event PriceDataUpdate( IERC20Token indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight ); constructor( IDSToken _token, IContractRegistry _registry, uint32 _maxConversionFee ) LiquidityPoolConverter(_token, _registry, _maxConversionFee) public { } function converterType() public pure override returns (uint16) { return 1; } function acceptAnchorOwnership() public override ownerOnly { super.acceptAnchorOwnership(); emit Activation(converterType(), anchor, true); } function addReserve(IERC20Token _token, uint32 _weight) public override ownerOnly { super.addReserve(_token, _weight); isStandardPool = reserveTokens.length == 2 && reserves[reserveTokens[0]].weight == 500000 && reserves[reserveTokens[1]].weight == 500000; } function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public view override active validReserve(_sourceToken) validReserve(_targetToken) returns (uint256, uint256) { require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET"); uint256 amount = IBancorFormula(addressOf(BANCOR_FORMULA)).crossReserveTargetAmount( reserveBalance(_sourceToken), reserves[_sourceToken].weight, reserveBalance(_targetToken), reserves[_targetToken].weight, _amount ); uint256 fee = calculateFee(amount); return (amount - fee, fee); } function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) internal override returns (uint256) { (uint256 amount, uint256 fee) = targetAmountAndFee(_sourceToken, _targetToken, _amount); require(amount != 0, "ERR_ZERO_TARGET_AMOUNT"); assert(amount < reserveBalance(_targetToken)); if (_sourceToken == ETH_RESERVE_ADDRESS) require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); else require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserveBalance(_sourceToken)) >= _amount, "ERR_INVALID_AMOUNT"); syncReserveBalance(_sourceToken); reserves[_targetToken].balance = reserves[_targetToken].balance.sub(amount); if (_targetToken == ETH_RESERVE_ADDRESS) _beneficiary.transfer(amount); else safeTransfer(_targetToken, _beneficiary, amount); if (isStandardPool && prevAverageRateUpdateTime < time()) { prevAverageRate = recentAverageRate(); prevAverageRateUpdateTime = time(); } return amount; } function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) internal override returns (uint256) { (uint256 amount, uint256 fee) = targetAmountAndFee(_sourceToken, _targetToken, _amount); require(amount != 0, "ERR_ZERO_TARGET_AMOUNT"); assert(amount < reserveBalance(_targetToken)); if (_sourceToken == ETH_RESERVE_ADDRESS) require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); else require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserveBalance(_sourceToken)) >= _amount, "ERR_INVALID_AMOUNT"); syncReserveBalance(_sourceToken); reserves[_targetToken].balance = reserves[_targetToken].balance.sub(amount); if (_targetToken == ETH_RESERVE_ADDRESS) _beneficiary.transfer(amount); else safeTransfer(_targetToken, _beneficiary, amount); if (isStandardPool && prevAverageRateUpdateTime < time()) { prevAverageRate = recentAverageRate(); prevAverageRateUpdateTime = time(); } return amount; } dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee); dispatchTokenRateUpdateEvents(_sourceToken, _targetToken); function recentAverageRate(IERC20Token _token) external view returns (uint256, uint256) { require(isStandardPool, "ERR_NON_STANDARD_POOL"); Fraction memory rate = recentAverageRate(); if (_token == reserveTokens[0]) { return (rate.n, rate.d); } return (rate.d, rate.n); } function recentAverageRate(IERC20Token _token) external view returns (uint256, uint256) { require(isStandardPool, "ERR_NON_STANDARD_POOL"); Fraction memory rate = recentAverageRate(); if (_token == reserveTokens[0]) { return (rate.n, rate.d); } return (rate.d, rate.n); } function recentAverageRate() internal view returns (Fraction memory) { uint256 timeElapsed = time() - prevAverageRateUpdateTime; if (timeElapsed == 0) { return prevAverageRate; } uint256 currentRateD = reserves[reserveTokens[0]].balance; if (timeElapsed >= AVERAGE_RATE_PERIOD) { } uint256 x = prevAverage.d.mul(currentRateN); uint256 y = prevAverage.n.mul(currentRateD); uint256 newRateD = prevAverage.d.mul(currentRateD).mul(AVERAGE_RATE_PERIOD); (newRateN, newRateD) = Math.reducedRatio(newRateN, newRateD, MAX_RATE_FACTOR_LOWER_BOUND); } function recentAverageRate() internal view returns (Fraction memory) { uint256 timeElapsed = time() - prevAverageRateUpdateTime; if (timeElapsed == 0) { return prevAverageRate; } uint256 currentRateD = reserves[reserveTokens[0]].balance; if (timeElapsed >= AVERAGE_RATE_PERIOD) { } uint256 x = prevAverage.d.mul(currentRateN); uint256 y = prevAverage.n.mul(currentRateD); uint256 newRateD = prevAverage.d.mul(currentRateD).mul(AVERAGE_RATE_PERIOD); (newRateN, newRateD) = Math.reducedRatio(newRateN, newRateD, MAX_RATE_FACTOR_LOWER_BOUND); } uint256 currentRateN = reserves[reserveTokens[1]].balance; function recentAverageRate() internal view returns (Fraction memory) { uint256 timeElapsed = time() - prevAverageRateUpdateTime; if (timeElapsed == 0) { return prevAverageRate; } uint256 currentRateD = reserves[reserveTokens[0]].balance; if (timeElapsed >= AVERAGE_RATE_PERIOD) { } uint256 x = prevAverage.d.mul(currentRateN); uint256 y = prevAverage.n.mul(currentRateD); uint256 newRateD = prevAverage.d.mul(currentRateD).mul(AVERAGE_RATE_PERIOD); (newRateN, newRateD) = Math.reducedRatio(newRateN, newRateD, MAX_RATE_FACTOR_LOWER_BOUND); } return Fraction({ n: currentRateN, d: currentRateD }); Fraction memory prevAverage = prevAverageRate; uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed)); return Fraction({ n: newRateN, d: newRateD }); function addLiquidity(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn) public payable protected active returns (uint256) { verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn); for (uint256 i = 0; i < _reserveTokens.length; i++) if (_reserveTokens[i] == ETH_RESERVE_ADDRESS) require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH"); if (msg.value > 0) { require(reserves[ETH_RESERVE_ADDRESS].isSet, "ERR_NO_ETH_RESERVE"); } } function addLiquidity(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn) public payable protected active returns (uint256) { verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn); for (uint256 i = 0; i < _reserveTokens.length; i++) if (_reserveTokens[i] == ETH_RESERVE_ADDRESS) require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH"); if (msg.value > 0) { require(reserves[ETH_RESERVE_ADDRESS].isSet, "ERR_NO_ETH_RESERVE"); } } uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); uint256 amount = addLiquidityToPool(_reserveTokens, _reserveAmounts, totalSupply); require(amount >= _minReturn, "ERR_RETURN_TOO_LOW"); IDSToken(address(anchor)).issue(msg.sender, amount); return amount; function removeLiquidity(uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts) public protected active returns (uint256[] memory) { verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount); uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); IDSToken(address(anchor)).destroy(msg.sender, _amount); return removeLiquidityFromPool(_reserveTokens, _reserveMinReturnAmounts, totalSupply, _amount); } function fund(uint256 _amount) public payable protected returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); uint256 supply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { IERC20Token reserveToken = reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(supply, rsvBalance, reserveRatio, _amount); if (reserveToken == ETH_RESERVE_ADDRESS) { if (msg.value > reserveAmount) { msg.sender.transfer(msg.value - reserveAmount); } else if (msg.value < reserveAmount) { require(msg.value == 0, "ERR_INVALID_ETH_VALUE"); safeTransferFrom(etherToken, msg.sender, address(this), reserveAmount); etherToken.withdraw(reserveAmount); } } else { safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); } reserves[reserveToken].balance = newReserveBalance; uint256 newPoolTokenSupply = supply.add(_amount); } } function fund(uint256 _amount) public payable protected returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); uint256 supply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { IERC20Token reserveToken = reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(supply, rsvBalance, reserveRatio, _amount); if (reserveToken == ETH_RESERVE_ADDRESS) { if (msg.value > reserveAmount) { msg.sender.transfer(msg.value - reserveAmount); } else if (msg.value < reserveAmount) { require(msg.value == 0, "ERR_INVALID_ETH_VALUE"); safeTransferFrom(etherToken, msg.sender, address(this), reserveAmount); etherToken.withdraw(reserveAmount); } } else { safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); } reserves[reserveToken].balance = newReserveBalance; uint256 newPoolTokenSupply = supply.add(_amount); } } function fund(uint256 _amount) public payable protected returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); uint256 supply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { IERC20Token reserveToken = reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(supply, rsvBalance, reserveRatio, _amount); if (reserveToken == ETH_RESERVE_ADDRESS) { if (msg.value > reserveAmount) { msg.sender.transfer(msg.value - reserveAmount); } else if (msg.value < reserveAmount) { require(msg.value == 0, "ERR_INVALID_ETH_VALUE"); safeTransferFrom(etherToken, msg.sender, address(this), reserveAmount); etherToken.withdraw(reserveAmount); } } else { safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); } reserves[reserveToken].balance = newReserveBalance; uint256 newPoolTokenSupply = supply.add(_amount); } } function fund(uint256 _amount) public payable protected returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); uint256 supply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { IERC20Token reserveToken = reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(supply, rsvBalance, reserveRatio, _amount); if (reserveToken == ETH_RESERVE_ADDRESS) { if (msg.value > reserveAmount) { msg.sender.transfer(msg.value - reserveAmount); } else if (msg.value < reserveAmount) { require(msg.value == 0, "ERR_INVALID_ETH_VALUE"); safeTransferFrom(etherToken, msg.sender, address(this), reserveAmount); etherToken.withdraw(reserveAmount); } } else { safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); } reserves[reserveToken].balance = newReserveBalance; uint256 newPoolTokenSupply = supply.add(_amount); } } function fund(uint256 _amount) public payable protected returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); uint256 supply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { IERC20Token reserveToken = reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(supply, rsvBalance, reserveRatio, _amount); if (reserveToken == ETH_RESERVE_ADDRESS) { if (msg.value > reserveAmount) { msg.sender.transfer(msg.value - reserveAmount); } else if (msg.value < reserveAmount) { require(msg.value == 0, "ERR_INVALID_ETH_VALUE"); safeTransferFrom(etherToken, msg.sender, address(this), reserveAmount); etherToken.withdraw(reserveAmount); } } else { safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); } reserves[reserveToken].balance = newReserveBalance; uint256 newPoolTokenSupply = supply.add(_amount); } } function fund(uint256 _amount) public payable protected returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); uint256 supply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { IERC20Token reserveToken = reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(supply, rsvBalance, reserveRatio, _amount); if (reserveToken == ETH_RESERVE_ADDRESS) { if (msg.value > reserveAmount) { msg.sender.transfer(msg.value - reserveAmount); } else if (msg.value < reserveAmount) { require(msg.value == 0, "ERR_INVALID_ETH_VALUE"); safeTransferFrom(etherToken, msg.sender, address(this), reserveAmount); etherToken.withdraw(reserveAmount); } } else { safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); } reserves[reserveToken].balance = newReserveBalance; uint256 newPoolTokenSupply = supply.add(_amount); } } uint256 newReserveBalance = rsvBalance.add(reserveAmount); emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply); dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight); IDSToken(address(anchor)).issue(msg.sender, _amount); return _amount; function liquidate(uint256 _amount) public protected returns (uint256[] memory) { require(_amount > 0, "ERR_ZERO_AMOUNT"); uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); IDSToken(address(anchor)).destroy(msg.sender, _amount); uint256[] memory reserveMinReturnAmounts = new uint256[](reserveTokens.length); for (uint256 i = 0; i < reserveMinReturnAmounts.length; i++) reserveMinReturnAmounts[i] = 1; return removeLiquidityFromPool(reserveTokens, reserveMinReturnAmounts, totalSupply, _amount); } function addLiquidityCost(IERC20Token[] memory _reserveTokens, uint256 _reserveTokenIndex, uint256 _reserveAmount) public view returns (uint256[] memory) { uint256[] memory reserveAmounts = new uint256[](_reserveTokens.length); uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = formula.fundSupplyAmount(totalSupply, reserves[_reserveTokens[_reserveTokenIndex]].balance, reserveRatio, _reserveAmount); for (uint256 i = 0; i < reserveAmounts.length; i++) reserveAmounts[i] = formula.fundCost(totalSupply, reserves[_reserveTokens[i]].balance, reserveRatio, amount); return reserveAmounts; } function addLiquidityReturn(IERC20Token _reserveToken, uint256 _reserveAmount) public view returns (uint256) { uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); return formula.fundSupplyAmount(totalSupply, reserves[_reserveToken].balance, reserveRatio, _reserveAmount); } function removeLiquidityReturn(uint256 _amount, IERC20Token[] memory _reserveTokens) public view returns (uint256[] memory) { uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); return removeLiquidityReserveAmounts(_amount, _reserveTokens, totalSupply, formula); } function verifyLiquidityInput(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _amount) private view { uint256 i; uint256 j; uint256 length = reserveTokens.length; require(length == _reserveTokens.length, "ERR_INVALID_RESERVE"); require(length == _reserveAmounts.length, "ERR_INVALID_AMOUNT"); for (i = 0; i < length; i++) { require(reserves[_reserveTokens[i]].isSet, "ERR_INVALID_RESERVE"); for (j = 0; j < length; j++) { if (reserveTokens[i] == _reserveTokens[j]) break; } } } function verifyLiquidityInput(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _amount) private view { uint256 i; uint256 j; uint256 length = reserveTokens.length; require(length == _reserveTokens.length, "ERR_INVALID_RESERVE"); require(length == _reserveAmounts.length, "ERR_INVALID_AMOUNT"); for (i = 0; i < length; i++) { require(reserves[_reserveTokens[i]].isSet, "ERR_INVALID_RESERVE"); for (j = 0; j < length; j++) { if (reserveTokens[i] == _reserveTokens[j]) break; } } } function verifyLiquidityInput(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _amount) private view { uint256 i; uint256 j; uint256 length = reserveTokens.length; require(length == _reserveTokens.length, "ERR_INVALID_RESERVE"); require(length == _reserveAmounts.length, "ERR_INVALID_AMOUNT"); for (i = 0; i < length; i++) { require(reserves[_reserveTokens[i]].isSet, "ERR_INVALID_RESERVE"); for (j = 0; j < length; j++) { if (reserveTokens[i] == _reserveTokens[j]) break; } } } require(j < length, "ERR_INVALID_RESERVE"); require(_reserveAmounts[i] > 0, "ERR_INVALID_AMOUNT"); require(_amount > 0, "ERR_ZERO_AMOUNT"); function addLiquidityToPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _totalSupply) private returns (uint256) { if (_totalSupply == 0) return addLiquidityToEmptyPool(_reserveTokens, _reserveAmounts); return addLiquidityToNonEmptyPool(_reserveTokens, _reserveAmounts, _totalSupply); } function addLiquidityToEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts) private returns (uint256) { uint256 amount = geometricMean(_reserveAmounts); for (uint256 i = 0; i < _reserveTokens.length; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 reserveAmount = _reserveAmounts[i]; safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); reserves[reserveToken].balance = reserveAmount; emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, reserveAmount, amount); dispatchPoolTokenRateUpdateEvent(amount, reserveToken, reserveAmount, reserves[reserveToken].weight); } } function addLiquidityToEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts) private returns (uint256) { uint256 amount = geometricMean(_reserveAmounts); for (uint256 i = 0; i < _reserveTokens.length; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 reserveAmount = _reserveAmounts[i]; safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); reserves[reserveToken].balance = reserveAmount; emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, reserveAmount, amount); dispatchPoolTokenRateUpdateEvent(amount, reserveToken, reserveAmount, reserves[reserveToken].weight); } } return amount; function addLiquidityToNonEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _totalSupply) private returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = getMinShare(formula, _totalSupply, _reserveTokens, _reserveAmounts); uint256 newPoolTokenSupply = _totalSupply.add(amount); for (uint256 i = 0; i < _reserveTokens.length; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(_totalSupply, rsvBalance, reserveRatio, amount); require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT"); assert(reserveAmount <= _reserveAmounts[i]); safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); msg.sender.transfer(_reserveAmounts[i] - reserveAmount); uint256 newReserveBalance = rsvBalance.add(reserveAmount); reserves[reserveToken].balance = newReserveBalance; emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply); dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight); } } function addLiquidityToNonEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _totalSupply) private returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = getMinShare(formula, _totalSupply, _reserveTokens, _reserveAmounts); uint256 newPoolTokenSupply = _totalSupply.add(amount); for (uint256 i = 0; i < _reserveTokens.length; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(_totalSupply, rsvBalance, reserveRatio, amount); require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT"); assert(reserveAmount <= _reserveAmounts[i]); safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); msg.sender.transfer(_reserveAmounts[i] - reserveAmount); uint256 newReserveBalance = rsvBalance.add(reserveAmount); reserves[reserveToken].balance = newReserveBalance; emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply); dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight); } } return amount; function removeLiquidityReserveAmounts(uint256 _amount, IERC20Token[] memory _reserveTokens, uint256 _totalSupply, IBancorFormula _formula) private view returns (uint256[] memory) { uint256[] memory reserveAmounts = new uint256[](_reserveTokens.length); for (uint256 i = 0; i < reserveAmounts.length; i++) reserveAmounts[i] = _formula.liquidateReserveAmount(_totalSupply, reserves[_reserveTokens[i]].balance, reserveRatio, _amount); return reserveAmounts; } function removeLiquidityFromPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts, uint256 _totalSupply, uint256 _amount) private returns (uint256[] memory) { syncReserveBalances(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 newPoolTokenSupply = _totalSupply.sub(_amount); uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, _reserveTokens, _totalSupply, formula); for (uint256 i = 0; i < _reserveTokens.length; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 reserveAmount = reserveAmounts[i]; require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT"); uint256 newReserveBalance = reserves[reserveToken].balance.sub(reserveAmount); reserves[reserveToken].balance = newReserveBalance; if (reserveToken == ETH_RESERVE_ADDRESS) msg.sender.transfer(reserveAmount); else safeTransfer(reserveToken, msg.sender, reserveAmount); emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply); dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight); } } function removeLiquidityFromPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts, uint256 _totalSupply, uint256 _amount) private returns (uint256[] memory) { syncReserveBalances(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 newPoolTokenSupply = _totalSupply.sub(_amount); uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, _reserveTokens, _totalSupply, formula); for (uint256 i = 0; i < _reserveTokens.length; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 reserveAmount = reserveAmounts[i]; require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT"); uint256 newReserveBalance = reserves[reserveToken].balance.sub(reserveAmount); reserves[reserveToken].balance = newReserveBalance; if (reserveToken == ETH_RESERVE_ADDRESS) msg.sender.transfer(reserveAmount); else safeTransfer(reserveToken, msg.sender, reserveAmount); emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply); dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight); } } return reserveAmounts; function getMinShare(IBancorFormula formula, uint256 _totalSupply, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts) private view returns (uint256) { uint256 minIndex = 0; for (uint256 i = 1; i < _reserveTokens.length; i++) { if (_reserveAmounts[i].mul(reserves[_reserveTokens[minIndex]].balance) < _reserveAmounts[minIndex].mul(reserves[_reserveTokens[i]].balance)) minIndex = i; } return formula.fundSupplyAmount(_totalSupply, reserves[_reserveTokens[minIndex]].balance, reserveRatio, _reserveAmounts[minIndex]); } function getMinShare(IBancorFormula formula, uint256 _totalSupply, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts) private view returns (uint256) { uint256 minIndex = 0; for (uint256 i = 1; i < _reserveTokens.length; i++) { if (_reserveAmounts[i].mul(reserves[_reserveTokens[minIndex]].balance) < _reserveAmounts[minIndex].mul(reserves[_reserveTokens[i]].balance)) minIndex = i; } return formula.fundSupplyAmount(_totalSupply, reserves[_reserveTokens[minIndex]].balance, reserveRatio, _reserveAmounts[minIndex]); } function decimalLength(uint256 _x) public pure returns (uint256) { uint256 y = 0; for (uint256 x = _x; x > 0; x /= 10) y++; return y; } function roundDivUnsafe(uint256 _n, uint256 _d) public pure returns (uint256) { return (_n + _d / 2) / _d; } function geometricMean(uint256[] memory _values) public pure returns (uint256) { uint256 numOfDigits = 0; uint256 length = _values.length; for (uint256 i = 0; i < length; i++) numOfDigits += decimalLength(_values[i]); return uint256(10) ** (roundDivUnsafe(numOfDigits, length) - 1); } function dispatchTokenRateUpdateEvents(IERC20Token _sourceToken, IERC20Token _targetToken) private { uint256 poolTokenSupply = IDSToken(address(anchor)).totalSupply(); uint256 sourceReserveBalance = reserveBalance(_sourceToken); uint256 targetReserveBalance = reserveBalance(_targetToken); uint32 sourceReserveWeight = reserves[_sourceToken].weight; uint32 targetReserveWeight = reserves[_targetToken].weight; uint256 rateN = targetReserveBalance.mul(sourceReserveWeight); uint256 rateD = sourceReserveBalance.mul(targetReserveWeight); emit TokenRateUpdate(_sourceToken, _targetToken, rateN, rateD); dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _sourceToken, sourceReserveBalance, sourceReserveWeight); dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _targetToken, targetReserveBalance, targetReserveWeight); emit PriceDataUpdate(_sourceToken, poolTokenSupply, sourceReserveBalance, sourceReserveWeight); emit PriceDataUpdate(_targetToken, poolTokenSupply, targetReserveBalance, targetReserveWeight); } function dispatchPoolTokenRateUpdateEvent(uint256 _poolTokenSupply, IERC20Token _reserveToken, uint256 _reserveBalance, uint32 _reserveWeight) private { emit TokenRateUpdate(IDSToken(address(anchor)), _reserveToken, _reserveBalance.mul(PPM_RESOLUTION), _poolTokenSupply.mul(_reserveWeight)); } function time() internal view virtual returns (uint256) { return now; } }
15,662,505
[ 1, 48, 18988, 24237, 8828, 331, 21, 14768, 1021, 4501, 372, 24237, 2845, 331, 21, 6027, 353, 279, 29158, 1177, 434, 279, 6027, 716, 20754, 281, 279, 28937, 25732, 3850, 4501, 372, 24237, 2845, 18, 25067, 11376, 16000, 848, 1240, 4906, 400, 264, 3324, 16, 326, 4529, 2845, 1664, 353, 576, 400, 264, 3324, 598, 6437, 9, 19, 3361, 9, 5376, 18, 19, 326, 3879, 434, 813, 9830, 1368, 2236, 1347, 21046, 326, 8399, 23713, 340, 4993, 638, 309, 326, 2845, 353, 279, 576, 400, 264, 3324, 342, 6437, 9, 19, 3361, 9, 5376, 2845, 16, 629, 3541, 1338, 1399, 316, 4529, 16000, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 18988, 24237, 2864, 58, 21, 5072, 353, 511, 18988, 24237, 2864, 5072, 288, 203, 565, 1450, 2361, 364, 380, 31, 203, 203, 565, 10897, 1136, 1345, 2713, 225, 2437, 1345, 273, 10897, 1136, 1345, 12, 20, 6511, 6840, 5540, 24, 5340, 39, 21, 72, 22, 4848, 18096, 23, 71, 38, 23, 41, 20, 42, 7677, 8522, 41, 22, 40, 9401, 1966, 22, 71, 41, 23, 3600, 1769, 203, 565, 2254, 5034, 2713, 5381, 4552, 67, 24062, 67, 26835, 67, 23085, 67, 19318, 273, 404, 73, 5082, 31, 203, 377, 203, 565, 2254, 5034, 3238, 5381, 432, 2204, 2833, 67, 24062, 67, 28437, 273, 1728, 6824, 31, 203, 203, 565, 1426, 1071, 353, 8336, 2864, 273, 629, 31, 203, 203, 203, 565, 871, 20137, 751, 1891, 12, 203, 3639, 467, 654, 39, 3462, 1345, 8808, 389, 23159, 1345, 16, 203, 3639, 2254, 5034, 389, 2316, 3088, 1283, 16, 203, 3639, 2254, 5034, 389, 23159, 13937, 16, 203, 3639, 2254, 1578, 389, 23159, 6544, 203, 565, 11272, 203, 203, 565, 3885, 12, 203, 3639, 1599, 882, 969, 389, 2316, 16, 203, 3639, 467, 8924, 4243, 389, 9893, 16, 203, 3639, 2254, 1578, 389, 1896, 6814, 14667, 203, 565, 262, 203, 3639, 511, 18988, 24237, 2864, 5072, 24899, 2316, 16, 389, 9893, 16, 389, 1896, 6814, 14667, 13, 203, 3639, 1071, 203, 203, 565, 288, 203, 565, 289, 203, 203, 565, 445, 6027, 559, 1435, 1071, 16618, 3849, 1135, 261, 11890, 2313, 13, 288, 203, 3639, 327, 404, 31, 203, 565, 289, 203, 203, 565, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Ganache { string message = ""; uint [] list; // Publica un mensaje en la cadena de bloques function setMessage(string memory _message) public { message = _message; } // Visualizar el mensaje de la cadena de bloques function getMessage() public view returns (string memory) { return message; } }
Visualizar el mensaje de la cadena de bloques
function getMessage() public view returns (string memory) { return message; }
5,526,525
[ 1, 25780, 31707, 415, 312, 773, 4365, 73, 443, 7125, 28451, 24457, 443, 324, 383, 29896, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2381, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 883, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /** * @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 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 totalTokens; } /** * @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) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_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 Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @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 onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @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)); addToken(_to, _tokenId); emit Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); emit Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; emit Approval(_owner, 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 addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.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 removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; 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; totalTokens = totalTokens.sub(1); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } contract HeroesToken is ERC721Token, CanReclaimToken { using SafeMath for uint256; event Bought (uint256 indexed _tokenId, address indexed _owner, uint256 _price); event Sold (uint256 indexed _tokenId, address indexed _owner, uint256 _price); uint256[] private listedTokens; mapping (uint256 => uint256) private priceOfToken; uint256[4] private limits = [0.05 ether, 0.5 ether, 5.0 ether]; uint256[4] private fees = [6, 5, 4, 3]; // 6%, 5%; 4%, 3% uint256[4] private increases = [200, 150, 130, 120]; // +100%, +50%; +30%, +20% function HeroesToken() ERC721Token() public {} function mint(address _to, uint256 _tokenId, uint256 _price) public onlyOwner { require(_to != address(this)); super._mint(_to, _tokenId); listedTokens.push(_tokenId); priceOfToken[_tokenId] = _price; } function priceOf(uint256 _tokenId) public view returns (uint256) { return priceOfToken[_tokenId]; } function calculateFee(uint256 _price) public view returns (uint256) { if (_price < limits[0]) { return _price.mul(fees[0]).div(100); } else if (_price < limits[1]) { return _price.mul(fees[1]).div(100); } else if (_price < limits[2]) { return _price.mul(fees[2]).div(100); } else { return _price.mul(fees[3]).div(100); } } function calculatePrice(uint256 _price) public view returns (uint256) { if (_price < limits[0]) { return _price.mul(increases[0]).div(100 - fees[0]); } else if (_price < limits[1]) { return _price.mul(increases[1]).div(100 - fees[1]); } else if (_price < limits[2]) { return _price.mul(increases[2]).div(100 - fees[2]); } else { return _price.mul(increases[3]).div(100 - fees[3]); } } function buy(uint256 _tokenId) public payable { require(priceOf(_tokenId) > 0); require(ownerOf(_tokenId) != address(0)); require(msg.value >= priceOf(_tokenId)); require(ownerOf(_tokenId) != msg.sender); require(!isContract(msg.sender)); require(msg.sender != address(0)); address oldOwner = ownerOf(_tokenId); address newOwner = msg.sender; uint256 price = priceOf(_tokenId); uint256 excess = msg.value.sub(price); super.clearApprovalAndTransfer(oldOwner, newOwner, _tokenId); priceOfToken[_tokenId] = calculatePrice(price); emit Bought(_tokenId, newOwner, price); emit Sold(_tokenId, oldOwner, price); uint256 fee = calculateFee(price); oldOwner.transfer(price.sub(fee)); if (excess > 0) { newOwner.transfer(excess); } } function withdrawAll() public onlyOwner { owner.transfer(address(this).balance); } function withdrawAmount(uint256 _amount) public onlyOwner { owner.transfer(_amount); } function listedTokensAsBytes(uint256 _from, uint256 _to) public constant returns (bytes) { require(_from >= 0); require(_to >= _from); require(_to < listedTokens.length); // Size of bytes uint256 size = 32 * (_to - _from + 1); uint256 counter = 0; bytes memory b = new bytes(size); for (uint256 x = _from; x < _to + 1; x++) { uint256 elem = listedTokens[x]; for (uint y = 0; y < 32; y++) { b[counter] = byte(uint8(elem / (2 ** (8 * (31 - y))))); counter++; } } return b; } function isContract(address _addr) internal view returns (bool) { uint size; assembly { size := extcodesize(_addr) } return size > 0; } }
+100%, +50%; +30%, +20%
uint256[4] private increases = [200, 150, 130, 120];
966,892
[ 1, 15, 6625, 9, 16, 397, 3361, 9, 31, 397, 5082, 9, 16, 397, 3462, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 63, 24, 65, 3238, 7033, 3304, 273, 306, 6976, 16, 18478, 16, 404, 5082, 16, 15743, 15533, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x271300F4f2a5eab42D10198A1F91C5b7Ec70dE02/sources/SougenGenesis.sol
File: contracts/GenesisPass.sol
contract SougenGenesis is ERC721, Ownable { using ECDSA for bytes32; using Strings for uint256; using Counters for Counters.Counter; address private _systemAddress = 0x5dA24Ea1db0358811cB98Be06A82108c6878355B; mapping(string => bool) public _usedNonces; mapping(address => uint) public _walletMintStatus; Counters.Counter private supply; string public uriSuffix = '.json'; uint256 public cost = 0.02 ether; uint256 public publicCost = 0.03 ether; uint256 public maxSupply = 8888; uint256 public maxMint = 3; uint256 public maxMintForGiveaway = 88; bool public paused = true; bool public wlOpen = false; bool public publicOpen = false; bool public revealed = false; event mintSuccess(address indexed _from, uint256 amount, uint256 supply); constructor() ERC721('Sougen Genesis Collection', 'SGC') {} function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId } pragma solidity >=0.7.0 <0.9.0; function totalSupply() public view returns (uint256) { return supply.current(); } modifier mintCompliance(uint256 _mintAmount) { require(!paused, 'Contract is paused'); require(_mintAmount > 0 && _mintAmount <= maxMint, 'Invalid mint amount!'); require( supply.current() + _mintAmount <= maxSupply, 'Max supply exceeded!' ); require( (balanceOf(msg.sender) + _mintAmount) <= maxMint, 'Wallet limit exceeded!' ); _; } function mint( uint256 _mintAmount, string memory nonce, bytes32 hash, bytes memory signature ) public payable mintCompliance(_mintAmount) { require(wlOpen, 'Whitelist sale is close'); require(msg.value >= cost * _mintAmount, 'Insufficient funds'); require(matchSigner(hash, signature), 'Plz mint through website'); require(!_usedNonces[nonce], 'Hash reused'); require( hashTransaction(msg.sender, _mintAmount, nonce) == hash, 'Hash failed' ); require( _walletMintStatus[msg.sender] + _mintAmount <= 3, 'Wallet limit reached' ); require(supply.current() + _mintAmount <= 4444, 'Max WL supply exceeded!'); _usedNonces[nonce] = true; _walletMintStatus[msg.sender] += _mintAmount; _mintLoop(msg.sender, _mintAmount); } function publicMint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(publicOpen, 'Public sale is close'); require(msg.value >= publicCost * _mintAmount, 'Insufficient funds!'); _mintLoop(msg.sender, _mintAmount); } function matchSigner(bytes32 hash, bytes memory signature) public view returns (bool) { return _systemAddress == hash.toEthSignedMessageHash().recover(signature); } function hashTransaction( address sender, uint256 amount, string memory nonce ) public view returns (bytes32) { bytes32 hash = keccak256( abi.encodePacked(sender, amount, nonce, address(this)) ); return hash; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token' ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix) ) : ''; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token' ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix) ) : ''; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setPublicCost(uint256 _cost) public onlyOwner { publicCost = _cost; } function setMaxMint(uint256 _maxMint) public onlyOwner { maxMint = _maxMint; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function setPublicOpen(bool _state) public onlyOwner { publicOpen = _state; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setMaxSupply(uint256 _maxMSupply) public onlyOwner { maxSupply = _maxMSupply; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function withdraw() public onlyOwner { (bool fs, ) = payable(0x7c8fcBEc30A1e97EBA14E8dB5d195c1eE5f63221).call{ value: address(this).balance * 50 / 100 }(''); require(fs); (bool os, ) = payable(0xC9ce49d16030fedA01D01F7C78e2E234daA5A2e1).call{ value: address(this).balance }(''); require(os); } function withdraw() public onlyOwner { (bool fs, ) = payable(0x7c8fcBEc30A1e97EBA14E8dB5d195c1eE5f63221).call{ value: address(this).balance * 50 / 100 }(''); require(fs); (bool os, ) = payable(0xC9ce49d16030fedA01D01F7C78e2E234daA5A2e1).call{ value: address(this).balance }(''); require(os); } function withdraw() public onlyOwner { (bool fs, ) = payable(0x7c8fcBEc30A1e97EBA14E8dB5d195c1eE5f63221).call{ value: address(this).balance * 50 / 100 }(''); require(fs); (bool os, ) = payable(0xC9ce49d16030fedA01D01F7C78e2E234daA5A2e1).call{ value: address(this).balance }(''); require(os); } function mintForGiveaway() public onlyOwner { require( balanceOf(msg.sender) <= maxMintForGiveaway, 'Wallet limit exceeded!' ); _mintLoop(msg.sender, maxMintForGiveaway); } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } emit mintSuccess(_receiver, _mintAmount, supply.current()); } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } emit mintSuccess(_receiver, _mintAmount, supply.current()); } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
15,677,464
[ 1, 812, 30, 20092, 19, 7642, 16786, 6433, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6155, 637, 275, 7642, 16786, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 225, 1450, 7773, 19748, 364, 1731, 1578, 31, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 225, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 225, 1758, 3238, 389, 4299, 1887, 273, 374, 92, 25, 72, 37, 3247, 41, 69, 21, 1966, 4630, 25, 5482, 2499, 71, 38, 10689, 1919, 7677, 37, 11149, 21770, 71, 9470, 8285, 23, 2539, 38, 31, 203, 225, 2874, 12, 1080, 516, 1426, 13, 1071, 389, 3668, 3989, 764, 31, 203, 225, 2874, 12, 2867, 516, 2254, 13, 1071, 389, 19177, 49, 474, 1482, 31, 203, 203, 225, 9354, 87, 18, 4789, 3238, 14467, 31, 203, 203, 225, 533, 1071, 2003, 5791, 273, 2418, 1977, 13506, 203, 203, 225, 2254, 5034, 1071, 6991, 273, 374, 18, 3103, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 1071, 8018, 273, 374, 18, 4630, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 943, 3088, 1283, 273, 1725, 5482, 28, 31, 203, 225, 2254, 5034, 1071, 943, 49, 474, 273, 890, 31, 203, 225, 2254, 5034, 1071, 943, 49, 474, 1290, 43, 688, 26718, 273, 24153, 31, 203, 203, 225, 1426, 1071, 17781, 273, 638, 31, 203, 225, 1426, 1071, 19564, 3678, 273, 629, 31, 203, 225, 1426, 1071, 1071, 3678, 273, 629, 31, 203, 225, 1426, 1071, 283, 537, 18931, 273, 629, 31, 203, 203, 225, 871, 312, 474, 4510, 12, 2867, 8808, 389, 2080, 16, 2254, 5034, 3844, 16, 2254, 5034, 2 ]
// Sources flattened with hardhat v2.6.8 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // 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); } /** * @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] 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 @openzeppelin/contracts/utils/structs/[email protected] pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File @openzeppelin/contracts/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/pool/HCPEPool.sol pragma solidity >=0.8.9; /** * @title HC PE Pool Contract * @author HASHLAND-TEAM * @notice In this contract PE round users can harvest HC */ contract HCPEPool is ReentrancyGuard { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; IERC20 public hc; uint256 public constant blockPerDay = 28800; uint256 public constant blockPerYear = blockPerDay * 365; uint256 public constant blockPerQuarter = blockPerYear / 4; uint256 public constant hcStartBlock = 12507000; uint256 public constant releaseStartBlock = hcStartBlock + blockPerQuarter; uint256 public constant releaseEndBlock = releaseStartBlock + blockPerYear; uint256 public constant releasedTotalToken = (120e4 * 1e18 * 90) / 100; uint256 public constant tokenPerBlock = releasedTotalToken / blockPerYear; uint256 public lastRewardBlock = releaseStartBlock; uint256 public stake; uint256 public accTokenPerStake; uint256 public releasedToken; uint256 public harvestedToken; mapping(address => uint256) public userStake; mapping(address => uint256) public userLastAccTokenPerStake; mapping(address => uint256) public userStoredToken; mapping(address => uint256) public userHarvestedToken; EnumerableSet.AddressSet private users; event HarvestToken(address indexed user, uint256 amount); /** * @param hcAddr Initialize HC Address * @param userAddrs Initialize users * @param userStakes Initialize user stake */ constructor( address hcAddr, address[] memory userAddrs, uint256[] memory userStakes ) { require( userAddrs.length == userStakes.length, "Data length does not match" ); hc = IERC20(hcAddr); for (uint256 i = 0; i < userAddrs.length; i++) { userStake[userAddrs[i]] += userStakes[i]; stake += userStakes[i]; users.add(userAddrs[i]); } } /** * @dev Harvest Token */ function harvestToken() external nonReentrant { updatePool(); uint256 pendingToken = (userStake[msg.sender] * (accTokenPerStake - userLastAccTokenPerStake[msg.sender])) / 1e18; uint256 amount = userStoredToken[msg.sender] + pendingToken; require(amount > 0, "Not enough token to harvest"); userStoredToken[msg.sender] = 0; userLastAccTokenPerStake[msg.sender] = accTokenPerStake; userHarvestedToken[msg.sender] += amount; harvestedToken += amount; hc.safeTransfer(msg.sender, amount); emit HarvestToken(msg.sender, amount); } /** * @dev Get Token Total Rewards of a User */ function getTokenTotalRewards(address user) external view returns (uint256) { return userHarvestedToken[user] + getTokenRewards(user); } /** * @dev Get Users Length */ function getUsersLength() external view returns (uint256) { return users.length(); } /** * @dev Get Users by Size */ function getUsersBySize(uint256 cursor, uint256 size) external view returns (address[] memory, uint256) { uint256 length = size; if (length > users.length() - cursor) { length = users.length() - cursor; } address[] memory values = new address[](length); for (uint256 i = 0; i < length; i++) { values[i] = users.at(cursor + i); } return (values, cursor + length); } /** * @dev Update Pool */ function updatePool() public { if (block.number <= lastRewardBlock) { return; } uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { uint256 amount = tokenPerBlock * (rewardsBlock - lastRewardBlock); accTokenPerStake += (amount * 1e18) / stake; releasedToken += amount; } lastRewardBlock = block.number; } /** * @dev Get Token Rewards of a User */ function getTokenRewards(address user) public view returns (uint256) { uint256 accTokenPerStakeTemp = accTokenPerStake; uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { accTokenPerStakeTemp += (tokenPerBlock * (rewardsBlock - lastRewardBlock) * 1e18) / stake; } return userStoredToken[user] + ((userStake[user] * (accTokenPerStakeTemp - userLastAccTokenPerStake[user])) / 1e18); } }
* @title HC PE Pool Contract @author HASHLAND-TEAM @notice In this contract PE round users can harvest HC/
contract HCPEPool is ReentrancyGuard { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; IERC20 public hc; uint256 public constant blockPerDay = 28800; uint256 public constant blockPerYear = blockPerDay * 365; uint256 public constant blockPerQuarter = blockPerYear / 4; uint256 public constant hcStartBlock = 12507000; uint256 public constant releaseStartBlock = hcStartBlock + blockPerQuarter; uint256 public constant releaseEndBlock = releaseStartBlock + blockPerYear; uint256 public constant releasedTotalToken = (120e4 * 1e18 * 90) / 100; uint256 public constant tokenPerBlock = releasedTotalToken / blockPerYear; uint256 public lastRewardBlock = releaseStartBlock; uint256 public stake; uint256 public accTokenPerStake; uint256 public releasedToken; uint256 public harvestedToken; mapping(address => uint256) public userStake; mapping(address => uint256) public userLastAccTokenPerStake; mapping(address => uint256) public userStoredToken; mapping(address => uint256) public userHarvestedToken; EnumerableSet.AddressSet private users; event HarvestToken(address indexed user, uint256 amount); constructor( address hcAddr, address[] memory userAddrs, uint256[] memory userStakes ) { require( userAddrs.length == userStakes.length, "Data length does not match" ); hc = IERC20(hcAddr); for (uint256 i = 0; i < userAddrs.length; i++) { userStake[userAddrs[i]] += userStakes[i]; stake += userStakes[i]; users.add(userAddrs[i]); } } ) { require( userAddrs.length == userStakes.length, "Data length does not match" ); hc = IERC20(hcAddr); for (uint256 i = 0; i < userAddrs.length; i++) { userStake[userAddrs[i]] += userStakes[i]; stake += userStakes[i]; users.add(userAddrs[i]); } } function harvestToken() external nonReentrant { updatePool(); uint256 pendingToken = (userStake[msg.sender] * (accTokenPerStake - userLastAccTokenPerStake[msg.sender])) / 1e18; uint256 amount = userStoredToken[msg.sender] + pendingToken; require(amount > 0, "Not enough token to harvest"); userStoredToken[msg.sender] = 0; userLastAccTokenPerStake[msg.sender] = accTokenPerStake; userHarvestedToken[msg.sender] += amount; harvestedToken += amount; hc.safeTransfer(msg.sender, amount); emit HarvestToken(msg.sender, amount); } function getTokenTotalRewards(address user) external view returns (uint256) { return userHarvestedToken[user] + getTokenRewards(user); } function getUsersLength() external view returns (uint256) { return users.length(); } function getUsersBySize(uint256 cursor, uint256 size) external view returns (address[] memory, uint256) { uint256 length = size; if (length > users.length() - cursor) { length = users.length() - cursor; } address[] memory values = new address[](length); for (uint256 i = 0; i < length; i++) { values[i] = users.at(cursor + i); } return (values, cursor + length); } function getUsersBySize(uint256 cursor, uint256 size) external view returns (address[] memory, uint256) { uint256 length = size; if (length > users.length() - cursor) { length = users.length() - cursor; } address[] memory values = new address[](length); for (uint256 i = 0; i < length; i++) { values[i] = users.at(cursor + i); } return (values, cursor + length); } function getUsersBySize(uint256 cursor, uint256 size) external view returns (address[] memory, uint256) { uint256 length = size; if (length > users.length() - cursor) { length = users.length() - cursor; } address[] memory values = new address[](length); for (uint256 i = 0; i < length; i++) { values[i] = users.at(cursor + i); } return (values, cursor + length); } function updatePool() public { if (block.number <= lastRewardBlock) { return; } uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { uint256 amount = tokenPerBlock * (rewardsBlock - lastRewardBlock); accTokenPerStake += (amount * 1e18) / stake; releasedToken += amount; } lastRewardBlock = block.number; } function updatePool() public { if (block.number <= lastRewardBlock) { return; } uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { uint256 amount = tokenPerBlock * (rewardsBlock - lastRewardBlock); accTokenPerStake += (amount * 1e18) / stake; releasedToken += amount; } lastRewardBlock = block.number; } function updatePool() public { if (block.number <= lastRewardBlock) { return; } uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { uint256 amount = tokenPerBlock * (rewardsBlock - lastRewardBlock); accTokenPerStake += (amount * 1e18) / stake; releasedToken += amount; } lastRewardBlock = block.number; } function getTokenRewards(address user) public view returns (uint256) { uint256 accTokenPerStakeTemp = accTokenPerStake; uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { accTokenPerStakeTemp += (tokenPerBlock * (rewardsBlock - lastRewardBlock) * 1e18) / stake; } return userStoredToken[user] + ((userStake[user] * (accTokenPerStakeTemp - userLastAccTokenPerStake[user])) / 1e18); } function getTokenRewards(address user) public view returns (uint256) { uint256 accTokenPerStakeTemp = accTokenPerStake; uint256 rewardsBlock = releaseEndBlock < block.number ? releaseEndBlock : block.number; if (rewardsBlock > lastRewardBlock && stake > 0) { accTokenPerStakeTemp += (tokenPerBlock * (rewardsBlock - lastRewardBlock) * 1e18) / stake; } return userStoredToken[user] + ((userStake[user] * (accTokenPerStakeTemp - userLastAccTokenPerStake[user])) / 1e18); } }
12,868,300
[ 1, 23408, 16628, 8828, 13456, 225, 20857, 48, 4307, 17, 1448, 2192, 225, 657, 333, 6835, 16628, 3643, 3677, 848, 17895, 26923, 31979, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 31979, 1423, 2864, 353, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 11684, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 1203, 2173, 4245, 273, 576, 5482, 713, 31, 203, 565, 2254, 5034, 1071, 5381, 1203, 2173, 5593, 273, 1203, 2173, 4245, 380, 21382, 31, 203, 565, 2254, 5034, 1071, 5381, 1203, 2173, 928, 14153, 273, 1203, 2173, 5593, 342, 1059, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 11684, 1685, 1768, 273, 2593, 3361, 27, 3784, 31, 203, 565, 2254, 5034, 1071, 5381, 3992, 1685, 1768, 273, 11684, 1685, 1768, 397, 1203, 2173, 928, 14153, 31, 203, 565, 2254, 5034, 1071, 5381, 3992, 1638, 1768, 273, 3992, 1685, 1768, 397, 1203, 2173, 5593, 31, 203, 565, 2254, 5034, 1071, 5381, 15976, 5269, 1345, 273, 261, 22343, 73, 24, 380, 404, 73, 2643, 380, 8566, 13, 342, 2130, 31, 203, 565, 2254, 5034, 1071, 5381, 1147, 2173, 1768, 273, 15976, 5269, 1345, 342, 1203, 2173, 5593, 31, 203, 203, 565, 2254, 5034, 1071, 1142, 17631, 1060, 1768, 273, 3992, 1685, 1768, 31, 203, 203, 565, 2254, 5034, 1071, 384, 911, 31, 203, 565, 2254, 5034, 1071, 4078, 1345, 2173, 510, 911, 31, 203, 565, 2254, 5034, 1071, 15976, 1345, 31, 203, 565, 2254, 5034, 1071, 17895, 90, 3149, 1345, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 2 ]
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { FlexibleLeverageStrategyAdapter } from "../adapters/FlexibleLeverageStrategyAdapter.sol"; import { ICErc20 } from "../interfaces/ICErc20.sol"; import { ICompoundPriceOracle } from "../interfaces/ICompoundPriceOracle.sol"; import { IFLIStrategyAdapter } from "../interfaces/IFLIStrategyAdapter.sol"; import { IUniswapV2Router } from "../interfaces/IUniswapV2Router.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; /** * @title FLIRebalanceViewer * @author Set Protocol * * ETHFLI Rebalance viewer that returns whether a Compound oracle update should be forced before a rebalance goes through, if no * oracle update the type of rebalance transaction will be returned adhering to the enum specified in FlexibleLeverageStrategyAdapter */ contract FLIRebalanceViewer { using PreciseUnitMath for uint256; using SafeMath for uint256; /* ============ Enums ============ */ enum FLIRebalanceAction { NONE, // Indicates no rebalance action can be taken REBALANCE, // Indicates rebalance() function can be successfully called ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called RIPCORD, // Indicates ripcord() function can be successfully called ORACLE // Indicates Compound oracle update should be pushed } /* ============ State Variables ============ */ IUniswapV2Router public uniswapRouter; IFLIStrategyAdapter public strategyAdapter; address public cEther; /* ============ Constructor ============ */ constructor(IUniswapV2Router _uniswapRouter, IFLIStrategyAdapter _strategyAdapter, address _cEther) public { uniswapRouter = _uniswapRouter; strategyAdapter = _strategyAdapter; cEther = _cEther; } /* ============ External Functions ============ */ /** * Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the * logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with * 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance(), 3 = call ripcord(). Additionally, logic is added to check if an oracle update * should be forced to the Compound protocol ahead of the rebalance (4). * * @param _customMinLeverageRatio Min leverage ratio passed in by caller to trigger rebalance * @param _customMaxLeverageRatio Max leverage ratio passed in by caller to trigger rebalance * * return FLIRebalanceAction Enum detailing whether to do nothing, rebalance, iterateRebalance, ripcord, or update Compound oracle */ function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(FLIRebalanceAction) { FlexibleLeverageStrategyAdapter.ShouldRebalance adapterRebalanceState = strategyAdapter.shouldRebalanceWithBounds( _customMinLeverageRatio, _customMaxLeverageRatio ); if (adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.NONE) { return FLIRebalanceAction.NONE; } else if (adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.RIPCORD) { FlexibleLeverageStrategyAdapter.IncentiveSettings memory incentive = strategyAdapter.getIncentive(); bool updateOracle = _shouldOracleBeUpdated(incentive.incentivizedTwapMaxTradeSize, incentive.incentivizedSlippageTolerance); return updateOracle ? FLIRebalanceAction.ORACLE : FLIRebalanceAction.RIPCORD; } else { FlexibleLeverageStrategyAdapter.ExecutionSettings memory execution = strategyAdapter.getExecution(); FLIRebalanceAction rebalanceAction = adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.REBALANCE ? FLIRebalanceAction.REBALANCE : FLIRebalanceAction.ITERATE_REBALANCE; bool updateOracle = _shouldOracleBeUpdated(execution.twapMaxTradeSize, execution.slippageTolerance); return updateOracle ? FLIRebalanceAction.ORACLE : rebalanceAction; } } /* ============ Internal Functions ============ */ /** * Checks if the Compound oracles should be updated before executing any rebalance action. Updates must occur if the resulting trade would end up outside the * slippage bounds as calculated against the Compound oracle. Aligning the oracle more closely with market prices should allow rebalances to go through. * * @param _maxTradeSize Max trade size of rebalance action (varies whether its ripcord or normal rebalance) * @param _slippageTolerance Slippage tolerance of rebalance action (varies whether its ripcord or normal rebalance) * * return bool Boolean indicating whether oracle needs to be updated */ function _shouldOracleBeUpdated( uint256 _maxTradeSize, uint256 _slippageTolerance ) internal view returns (bool) { FlexibleLeverageStrategyAdapter.ContractSettings memory settings = strategyAdapter.getStrategy(); uint256 executionPrice; uint256 oraclePrice; if (strategyAdapter.getCurrentLeverageRatio() > strategyAdapter.getMethodology().targetLeverageRatio) { executionPrice = _getUniswapExecutionPrice(settings.borrowAsset, settings.collateralAsset, _maxTradeSize, false); oraclePrice = _getCompoundOraclePrice(settings.priceOracle, settings.targetBorrowCToken, settings.targetCollateralCToken); } else { executionPrice = _getUniswapExecutionPrice(settings.collateralAsset, settings.borrowAsset, _maxTradeSize, true); oraclePrice = _getCompoundOraclePrice(settings.priceOracle, settings.targetCollateralCToken, settings.targetBorrowCToken); } return executionPrice > oraclePrice.preciseMul(PreciseUnitMath.preciseUnit().add(_slippageTolerance)); } /** * Calculates Uniswap exection price by querying Uniswap for expected token flow amounts for a trade and implying market price. Returned value * is normalized to 18 decimals. * * @param _buyAsset Asset being bought on Uniswap * @param _sellAsset Asset being sold on Uniswap * @param _tradeSize Size of the trade in collateral units * @param _isBuyingCollateral Whether collateral is being bought or sold (used to determine which Uniswap function to call) * * return uint256 Implied Uniswap market price for pair, normalized to 18 decimals */ function _getUniswapExecutionPrice( address _buyAsset, address _sellAsset, uint256 _tradeSize, bool _isBuyingCollateral ) internal view returns (uint256) { address[] memory path = new address[](2); path[0] = _sellAsset; path[1] = _buyAsset; // Returned [sellAmount, buyAmount] uint256[] memory flows = _isBuyingCollateral ? uniswapRouter.getAmountsIn(_tradeSize, path) : uniswapRouter.getAmountsOut(_tradeSize, path); uint256 buyDecimals = uint256(10)**ERC20(_buyAsset).decimals(); uint256 sellDecimals = uint256(10)**ERC20(_sellAsset).decimals(); return flows[0].preciseDiv(sellDecimals).preciseDiv(flows[1].preciseDiv(buyDecimals)); } /** * Calculates Compound oracle price * * @param _priceOracle Compound price oracle * @param _cTokenBuyAsset CToken having net exposure increased (ie if net balance is short, decreasing short) * @param _cTokenSellAsset CToken having net exposure decreased (ie if net balance is short, increasing short) * * return uint256 Compound oracle price for pair, normalized to 18 decimals */ function _getCompoundOraclePrice( ICompoundPriceOracle _priceOracle, ICErc20 _cTokenBuyAsset, ICErc20 _cTokenSellAsset ) internal view returns (uint256) { uint256 buyPrice = _priceOracle.getUnderlyingPrice(address(_cTokenBuyAsset)); uint256 sellPrice = _priceOracle.getUnderlyingPrice(address(_cTokenSellAsset)); uint256 buyDecimals = address(_cTokenBuyAsset) == cEther ? PreciseUnitMath.preciseUnit() : uint256(10)**ERC20(_cTokenBuyAsset.underlying()).decimals(); uint256 sellDecimals = address(_cTokenSellAsset) == cEther ? PreciseUnitMath.preciseUnit() : uint256(10)**ERC20(_cTokenSellAsset.underlying()).decimals(); return buyPrice.mul(buyDecimals).preciseDiv(sellPrice.mul(sellDecimals)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { Math } from "@openzeppelin/contracts/math/Math.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { BaseAdapter } from "../lib/BaseAdapter.sol"; import { ICErc20 } from "../interfaces/ICErc20.sol"; import { IBaseManager } from "../interfaces/IBaseManager.sol"; import { IComptroller } from "../interfaces/IComptroller.sol"; import { ICompoundLeverageModule } from "../interfaces/ICompoundLeverageModule.sol"; import { ICompoundPriceOracle } from "../interfaces/ICompoundPriceOracle.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; /** * @title FlexibleLeverageStrategyAdapter * @author Set Protocol * * Smart contract that enables trustless leverage tokens using the flexible leverage methodology. This adapter is paired with the CompoundLeverageModule from Set * protocol where module interactions are invoked via the IBaseManager contract. Any leveraged token can be constructed as long as the collateral and borrow * asset is available on Compound. This adapter contract also allows the operator to set an ETH reward to incentivize keepers calling the rebalance function at * different leverage thresholds. */ contract FlexibleLeverageStrategyAdapter is BaseAdapter { using Address for address; using PreciseUnitMath for uint256; using SafeMath for uint256; /* ============ Enums ============ */ enum ShouldRebalance { NONE, // Indicates no rebalance action can be taken REBALANCE, // Indicates rebalance() function can be successfully called ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called RIPCORD // Indicates ripcord() function can be successfully called } /* ============ Structs ============ */ struct ActionInfo { uint256 collateralPrice; // Price of underlying in precise units (10e18) uint256 borrowPrice; // Price of underlying in precise units (10e18) uint256 collateralBalance; // Balance of underlying held in Compound in base units (e.g. USDC 10e6) uint256 borrowBalance; // Balance of underlying borrowed from Compound in base units uint256 collateralValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 borrowValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 setTotalSupply; // Total supply of SetToken } struct LeverageInfo { ActionInfo action; uint256 currentLeverageRatio; // Current leverage ratio of Set uint256 slippageTolerance; // Allowable percent trade slippage in preciseUnits (1% = 10^16) uint256 twapMaxTradeSize; // Max trade size in collateral units allowed for rebalance action } struct ContractSettings { ISetToken setToken; // Instance of leverage token ICompoundLeverageModule leverageModule; // Instance of Compound leverage module IComptroller comptroller; // Instance of Compound Comptroller ICompoundPriceOracle priceOracle; // Compound open oracle feed that returns prices accounting for decimals. e.g. USDC 6 decimals = 10^18 * 10^18 / 10^6 ICErc20 targetCollateralCToken; // Instance of target collateral cToken asset ICErc20 targetBorrowCToken; // Instance of target borrow cToken asset address collateralAsset; // Address of underlying collateral address borrowAsset; // Address of underlying borrow asset } struct MethodologySettings { uint256 targetLeverageRatio; // Long term target ratio in precise units (10e18) uint256 minLeverageRatio; // In precise units (10e18). If current leverage is below, rebalance target is this ratio uint256 maxLeverageRatio; // In precise units (10e18). If current leverage is above, rebalance target is this ratio uint256 recenteringSpeed; // % at which to rebalance back to target leverage in precise units (10e18) uint256 rebalanceInterval; // Period of time required since last rebalance timestamp in seconds } struct ExecutionSettings { uint256 unutilizedLeveragePercentage; // Percent of max borrow left unutilized in precise units (1% = 10e16) uint256 twapMaxTradeSize; // Max trade size in collateral base units uint256 twapCooldownPeriod; // Cooldown period required since last trade timestamp in seconds uint256 slippageTolerance; // % in precise units to price min token receive amount from trade quantities string exchangeName; // Name of exchange that is being used for leverage bytes exchangeData; // Arbitrary exchange data passed into rebalance function } struct IncentiveSettings { uint256 etherReward; // ETH reward for incentivized rebalances uint256 incentivizedLeverageRatio; // Leverage ratio for incentivized rebalances uint256 incentivizedSlippageTolerance; // Slippage tolerance percentage for incentivized rebalances uint256 incentivizedTwapCooldownPeriod; // TWAP cooldown in seconds for incentivized rebalances uint256 incentivizedTwapMaxTradeSize; // Max trade size for incentivized rebalances in collateral base units } /* ============ Events ============ */ event Engaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional); event Rebalanced( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional ); event RebalanceIterated( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional ); event RipcordCalled( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _rebalanceNotional, uint256 _etherIncentive ); event Disengaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional); event MethodologySettingsUpdated( uint256 _targetLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio, uint256 _recenteringSpeed, uint256 _rebalanceInterval ); event ExecutionSettingsUpdated( uint256 _unutilizedLeveragePercentage, uint256 _twapMaxTradeSize, uint256 _twapCooldownPeriod, uint256 _slippageTolerance, string _exchangeName, bytes _exchangeData ); event IncentiveSettingsUpdated( uint256 _etherReward, uint256 _incentivizedLeverageRatio, uint256 _incentivizedSlippageTolerance, uint256 _incentivizedTwapCooldownPeriod, uint256 _incentivizedTwapMaxTradeSize ); /* ============ Modifiers ============ */ /** * Throws if rebalance is currently in TWAP` */ modifier noRebalanceInProgress() { require(twapLeverageRatio == 0, "Rebalance is currently in progress"); _; } /* ============ State Variables ============ */ ContractSettings internal strategy; // Struct of contracts used in the strategy (SetToken, price oracles, leverage module etc) MethodologySettings internal methodology; // Struct containing methodology parameters ExecutionSettings internal execution; // Struct containing execution parameters IncentiveSettings internal incentive; // Struct containing incentive parameters for ripcord uint256 public twapLeverageRatio; // Stored leverage ratio to keep track of target between TWAP rebalances uint256 public lastTradeTimestamp; // Last rebalance timestamp. Must be past rebalance interval to rebalance /* ============ Constructor ============ */ /** * Instantiate addresses, methodology parameters, execution parameters, and incentive parameters. * * @param _manager Address of IBaseManager contract * @param _strategy Struct of contract addresses * @param _methodology Struct containing methodology parameters * @param _execution Struct containing execution parameters * @param _incentive Struct containing incentive parameters for ripcord */ constructor( IBaseManager _manager, ContractSettings memory _strategy, MethodologySettings memory _methodology, ExecutionSettings memory _execution, IncentiveSettings memory _incentive ) public BaseAdapter(_manager) { strategy = _strategy; methodology = _methodology; execution = _execution; incentive = _incentive; _validateSettings(methodology, execution, incentive); } /* ============ External Functions ============ */ /** * OPERATOR ONLY: Engage to target leverage ratio for the first time. SetToken will borrow debt position from Compound and trade for collateral asset. If target * leverage ratio is above max borrow or max trade size, then TWAP is kicked off. To complete engage if TWAP, any valid caller must call iterateRebalance until target * is met. */ function engage() external onlyOperator { ActionInfo memory engageInfo = _createActionInfo(); require(engageInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(engageInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(engageInfo.borrowBalance == 0, "Debt must be 0"); LeverageInfo memory leverageInfo = LeverageInfo({ action: engageInfo, currentLeverageRatio: PreciseUnitMath.preciseUnit(), // 1x leverage in precise units slippageTolerance: execution.slippageTolerance, twapMaxTradeSize: execution.twapMaxTradeSize }); // Calculate total rebalance units and kick off TWAP if above max borrow or max trade size ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true); _lever(leverageInfo, chunkRebalanceNotional); _updateRebalanceState( chunkRebalanceNotional, totalRebalanceNotional, methodology.targetLeverageRatio ); emit Engaged( leverageInfo.currentLeverageRatio, methodology.targetLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * ONLY EOA AND ALLOWED CALLER: Rebalance according to flexible leverage methodology. If current leverage ratio is between the max and min bounds, then rebalance * can only be called once the rebalance interval has elapsed since last timestamp. If outside the max and min, rebalance can be called anytime to bring leverage * ratio back to the max or min bounds. The methodology will determine whether to delever or lever. * * Note: If the calculated current leverage ratio is above the incentivized leverage ratio or in TWAP then rebalance cannot be called. Instead, you must call * ripcord() which is incentivized with a reward in Ether or iterateRebalance(). */ function rebalance() external onlyEOA onlyAllowedCaller(msg.sender) { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); _validateNormalRebalance(leverageInfo, methodology.rebalanceInterval); _validateNonTWAP(); uint256 newLeverageRatio = _calculateNewLeverageRatio(leverageInfo.currentLeverageRatio); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _handleRebalance(leverageInfo, newLeverageRatio); _updateRebalanceState(chunkRebalanceNotional, totalRebalanceNotional, newLeverageRatio); emit Rebalanced( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * ONLY EOA AND ALLOWED CALLER: Iterate a rebalance when in TWAP. TWAP cooldown period must have elapsed. If price moves advantageously, then exit without rebalancing * and clear TWAP state. This function can only be called when below incentivized leverage ratio and in TWAP state. */ function iterateRebalance() external onlyEOA onlyAllowedCaller(msg.sender) { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); _validateNormalRebalance(leverageInfo, execution.twapCooldownPeriod); _validateTWAP(); uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (!_isAdvantageousTWAP(leverageInfo.currentLeverageRatio)) { (chunkRebalanceNotional, totalRebalanceNotional) = _handleRebalance(leverageInfo, twapLeverageRatio); } // If not advantageous, then rebalance is skipped and chunk and total rebalance notional are both 0, which means TWAP state is // cleared _updateIterateState(chunkRebalanceNotional, totalRebalanceNotional); emit RebalanceIterated( leverageInfo.currentLeverageRatio, twapLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * ONLY EOA: In case the current leverage ratio exceeds the incentivized leverage threshold, the ripcord function can be called by anyone to return leverage ratio * back to the max leverage ratio. This function typically would only be called during times of high downside volatility and / or normal keeper malfunctions. The caller * of ripcord() will receive a reward in Ether. The ripcord function uses it's own TWAP cooldown period, slippage tolerance and TWAP max trade size which are typically * looser than in regular rebalances. */ function ripcord() external onlyEOA { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo( incentive.incentivizedSlippageTolerance, incentive.incentivizedTwapMaxTradeSize ); _validateRipcord(leverageInfo); ( uint256 chunkRebalanceNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.maxLeverageRatio, false); _delever(leverageInfo, chunkRebalanceNotional); _updateRipcordState(); uint256 etherTransferred = _transferEtherRewardToCaller(incentive.etherReward); emit RipcordCalled( leverageInfo.currentLeverageRatio, methodology.maxLeverageRatio, chunkRebalanceNotional, etherTransferred ); } /** * OPERATOR ONLY: Return leverage ratio to 1x and delever to repay loan. This can be used for upgrading or shutting down the strategy. SetToken will redeem * collateral position and trade for debt position to repay Compound. If the chunk rebalance size is less than the total notional size, then this function will * delever and repay entire borrow balance on Compound. If chunk rebalance size is above max borrow or max trade size, then operator must * continue to call this function to complete repayment of loan. The function iterateRebalance will not work. * * Note: Delever to 0 will likely result in additional units of the borrow asset added as equity on the SetToken due to oracle price / market price mismatch */ function disengage() external onlyOperator { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); uint256 newLeverageRatio = PreciseUnitMath.preciseUnit(); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false); if (totalRebalanceNotional > chunkRebalanceNotional) { _delever(leverageInfo, chunkRebalanceNotional); } else { _deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional); } emit Disengaged( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * OPERATOR ONLY: Set methodology settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be * in a rebalance. * * @param _newMethodologySettings Struct containing methodology parameters */ function setMethodologySettings(MethodologySettings memory _newMethodologySettings) external onlyOperator noRebalanceInProgress { methodology = _newMethodologySettings; _validateSettings(methodology, execution, incentive); emit MethodologySettingsUpdated( methodology.targetLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio, methodology.recenteringSpeed, methodology.rebalanceInterval ); } /** * OPERATOR ONLY: Set execution settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be * in a rebalance. * * @param _newExecutionSettings Struct containing execution parameters */ function setExecutionSettings(ExecutionSettings memory _newExecutionSettings) external onlyOperator noRebalanceInProgress { execution = _newExecutionSettings; _validateSettings(methodology, execution, incentive); emit ExecutionSettingsUpdated( execution.unutilizedLeveragePercentage, execution.twapMaxTradeSize, execution.twapCooldownPeriod, execution.slippageTolerance, execution.exchangeName, execution.exchangeData ); } /** * OPERATOR ONLY: Set incentive settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be * in a rebalance. * * @param _newIncentiveSettings Struct containing incentive parameters */ function setIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) external onlyOperator noRebalanceInProgress { incentive = _newIncentiveSettings; _validateSettings(methodology, execution, incentive); emit IncentiveSettingsUpdated( incentive.etherReward, incentive.incentivizedLeverageRatio, incentive.incentivizedSlippageTolerance, incentive.incentivizedTwapCooldownPeriod, incentive.incentivizedTwapMaxTradeSize ); } /** * OPERATOR ONLY: Withdraw entire balance of ETH in this contract to operator. Rebalance must not be in progress */ function withdrawEtherBalance() external onlyOperator noRebalanceInProgress { msg.sender.transfer(address(this).balance); } receive() external payable {} /* ============ External Getter Functions ============ */ /** * Get current leverage ratio. Current leverage ratio is defined as the USD value of the collateral divided by the USD value of the SetToken. Prices for collateral * and borrow asset are retrieved from the Compound Price Oracle. * * return currentLeverageRatio Current leverage ratio in precise units (10e18) */ function getCurrentLeverageRatio() public view returns(uint256) { ActionInfo memory currentLeverageInfo = _createActionInfo(); return _calculateCurrentLeverageRatio(currentLeverageInfo.collateralValue, currentLeverageInfo.borrowValue); } /** * Get current Ether incentive for when current leverage ratio exceeds incentivized leverage ratio and ripcord can be called. If ETH balance on the contract is * below the etherReward, then return the balance of ETH instead. * * return etherReward Quantity of ETH reward in base units (10e18) */ function getCurrentEtherIncentive() external view returns(uint256) { uint256 currentLeverageRatio = getCurrentLeverageRatio(); if (currentLeverageRatio >= incentive.incentivizedLeverageRatio) { // If ETH reward is below the balance on this contract, then return ETH balance on contract instead return incentive.etherReward < address(this).balance ? incentive.etherReward : address(this).balance; } else { return 0; } } /** * Helper that checks if conditions are met for rebalance or ripcord. Returns an enum with 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance() * 3 = call ripcord() * * return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action */ function shouldRebalance() external view returns(ShouldRebalance) { uint256 currentLeverageRatio = getCurrentLeverageRatio(); return _shouldRebalance(currentLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio); } /** * Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the * logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with * 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance()3 = call ripcord() * * @param _customMinLeverageRatio Min leverage ratio passed in by caller * @param _customMaxLeverageRatio Max leverage ratio passed in by caller * * return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action */ function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(ShouldRebalance) { require ( _customMinLeverageRatio <= methodology.minLeverageRatio && _customMaxLeverageRatio >= methodology.maxLeverageRatio, "Custom bounds must be valid" ); uint256 currentLeverageRatio = getCurrentLeverageRatio(); return _shouldRebalance(currentLeverageRatio, _customMinLeverageRatio, _customMaxLeverageRatio); } /** * Explicit getter functions for parameter structs are defined as workaround to issues fetching structs that have dynamic types. */ function getStrategy() external view returns (ContractSettings memory) { return strategy; } function getMethodology() external view returns (MethodologySettings memory) { return methodology; } function getExecution() external view returns (ExecutionSettings memory) { return execution; } function getIncentive() external view returns (IncentiveSettings memory) { return incentive; } /* ============ Internal Functions ============ */ /** * Calculate notional rebalance quantity, whether to chunk rebalance based on max trade size and max borrow and invoke lever on CompoundLeverageModule * */ function _lever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action); uint256 minReceiveCollateralUnits = _calculateMinCollateralReceiveUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance); bytes memory leverCallData = abi.encodeWithSignature( "lever(address,address,address,uint256,uint256,string,bytes)", address(strategy.setToken), strategy.borrowAsset, strategy.collateralAsset, borrowUnits, minReceiveCollateralUnits, execution.exchangeName, execution.exchangeData ); invokeManager(address(strategy.leverageModule), leverCallData); } /** * Calculate delever units Invoke delever on CompoundLeverageModule. */ function _delever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 minRepayUnits = _calculateMinRepayUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance, _leverageInfo.action); bytes memory deleverCallData = abi.encodeWithSignature( "delever(address,address,address,uint256,uint256,string,bytes)", address(strategy.setToken), strategy.collateralAsset, strategy.borrowAsset, collateralRebalanceUnits, minRepayUnits, execution.exchangeName, execution.exchangeData ); invokeManager(address(strategy.leverageModule), deleverCallData); } /** * Invoke deleverToZeroBorrowBalance on CompoundLeverageModule. */ function _deleverToZeroBorrowBalance( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { // Account for slippage tolerance in redeem quantity for the deleverToZeroBorrowBalance function uint256 maxCollateralRebalanceUnits = _chunkRebalanceNotional .preciseMul(PreciseUnitMath.preciseUnit().add(execution.slippageTolerance)) .preciseDiv(_leverageInfo.action.setTotalSupply); bytes memory deleverToZeroBorrowBalanceCallData = abi.encodeWithSignature( "deleverToZeroBorrowBalance(address,address,address,uint256,string,bytes)", address(strategy.setToken), strategy.collateralAsset, strategy.borrowAsset, maxCollateralRebalanceUnits, execution.exchangeName, execution.exchangeData ); invokeManager(address(strategy.leverageModule), deleverToZeroBorrowBalanceCallData); } /** * Check whether to delever or lever based on the current vs new leverage ratios. Used in the rebalance() and iterateRebalance() functions * * return uint256 Calculated notional to trade * return uint256 Total notional to rebalance over TWAP */ function _handleRebalance(LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio) internal returns(uint256, uint256) { uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (_newLeverageRatio < _leverageInfo.currentLeverageRatio) { ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, false); _delever(_leverageInfo, chunkRebalanceNotional); } else { ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, true); _lever(_leverageInfo, chunkRebalanceNotional); } return (chunkRebalanceNotional, totalRebalanceNotional); } /** * Create the leverage info struct to be used in internal functions * * return LeverageInfo Struct containing ActionInfo and other data */ function _getAndValidateLeveragedInfo(uint256 _slippageTolerance, uint256 _maxTradeSize) internal view returns(LeverageInfo memory) { ActionInfo memory actionInfo = _createActionInfo(); require(actionInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(actionInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(actionInfo.borrowBalance > 0, "Borrow balance must exist"); // Get current leverage ratio uint256 currentLeverageRatio = _calculateCurrentLeverageRatio( actionInfo.collateralValue, actionInfo.borrowValue ); return LeverageInfo({ action: actionInfo, currentLeverageRatio: currentLeverageRatio, slippageTolerance: _slippageTolerance, twapMaxTradeSize: _maxTradeSize }); } /** * Create the action info struct to be used in internal functions * * return ActionInfo Struct containing data used by internal lever and delever functions */ function _createActionInfo() internal view returns(ActionInfo memory) { ActionInfo memory rebalanceInfo; // IMPORTANT: Compound oracle returns prices adjusted for decimals. USDC is 6 decimals so $1 * 10^18 * 10^18 / 10^6 = 10^30 rebalanceInfo.collateralPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetCollateralCToken)); rebalanceInfo.borrowPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetBorrowCToken)); // Calculate stored exchange rate which does not trigger a state update uint256 cTokenBalance = strategy.targetCollateralCToken.balanceOf(address(strategy.setToken)); rebalanceInfo.collateralBalance = cTokenBalance.preciseMul(strategy.targetCollateralCToken.exchangeRateStored()); rebalanceInfo.borrowBalance = strategy.targetBorrowCToken.borrowBalanceStored(address(strategy.setToken)); rebalanceInfo.collateralValue = rebalanceInfo.collateralPrice.preciseMul(rebalanceInfo.collateralBalance); rebalanceInfo.borrowValue = rebalanceInfo.borrowPrice.preciseMul(rebalanceInfo.borrowBalance); rebalanceInfo.setTotalSupply = strategy.setToken.totalSupply(); return rebalanceInfo; } /** * Validate settings in constructor and setters when updating. */ function _validateSettings( MethodologySettings memory _methodology, ExecutionSettings memory _execution, IncentiveSettings memory _incentive ) internal pure { require ( _methodology.minLeverageRatio <= _methodology.targetLeverageRatio && _methodology.minLeverageRatio > 0, "Must be valid min leverage" ); require ( _methodology.maxLeverageRatio >= _methodology.targetLeverageRatio, "Must be valid max leverage" ); require ( _methodology.recenteringSpeed <= PreciseUnitMath.preciseUnit() && _methodology.recenteringSpeed > 0, "Must be valid recentering speed" ); require ( _execution.unutilizedLeveragePercentage <= PreciseUnitMath.preciseUnit(), "Unutilized leverage must be <100%" ); require ( _execution.slippageTolerance <= PreciseUnitMath.preciseUnit(), "Slippage tolerance must be <100%" ); require ( _incentive.incentivizedSlippageTolerance <= PreciseUnitMath.preciseUnit(), "Incentivized slippage tolerance must be <100%" ); require ( _incentive.incentivizedLeverageRatio >= _methodology.maxLeverageRatio, "Incentivized leverage ratio must be > max leverage ratio" ); require ( _methodology.rebalanceInterval >= _execution.twapCooldownPeriod, "Rebalance interval must be greater than TWAP cooldown period" ); require ( _execution.twapCooldownPeriod >= _incentive.incentivizedTwapCooldownPeriod, "TWAP cooldown must be greater than incentivized TWAP cooldown" ); require ( _execution.twapMaxTradeSize <= _incentive.incentivizedTwapMaxTradeSize, "TWAP max trade size must be less than incentivized TWAP max trade size" ); } /** * Validate that current leverage is below incentivized leverage ratio and cooldown / rebalance period has elapsed or outsize max/min bounds. Used * in rebalance() and iterateRebalance() functions */ function _validateNormalRebalance(LeverageInfo memory _leverageInfo, uint256 _coolDown) internal view { require(_leverageInfo.currentLeverageRatio < incentive.incentivizedLeverageRatio, "Must be below incentivized leverage ratio"); require( block.timestamp.sub(lastTradeTimestamp) > _coolDown || _leverageInfo.currentLeverageRatio > methodology.maxLeverageRatio || _leverageInfo.currentLeverageRatio < methodology.minLeverageRatio, "Cooldown not elapsed or not valid leverage ratio" ); } /** * Validate that current leverage is above incentivized leverage ratio and incentivized cooldown period has elapsed in ripcord() */ function _validateRipcord(LeverageInfo memory _leverageInfo) internal view { require(_leverageInfo.currentLeverageRatio >= incentive.incentivizedLeverageRatio, "Must be above incentivized leverage ratio"); // If currently in the midst of a TWAP rebalance, ensure that the cooldown period has elapsed require(lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp, "TWAP cooldown must have elapsed"); } /** * Validate TWAP in the iterateRebalance() function */ function _validateTWAP() internal view { require(twapLeverageRatio > 0, "Not in TWAP state"); } /** * Validate not TWAP in the rebalance() function */ function _validateNonTWAP() internal view { require(twapLeverageRatio == 0, "Must call iterate"); } /** * Check if price has moved advantageously while in the midst of the TWAP rebalance. This means the current leverage ratio has moved over/under * the stored TWAP leverage ratio on lever/delever so there is no need to execute a rebalance. Used in iterateRebalance() */ function _isAdvantageousTWAP(uint256 _currentLeverageRatio) internal view returns (bool) { return ( (twapLeverageRatio < methodology.targetLeverageRatio && _currentLeverageRatio >= twapLeverageRatio) || (twapLeverageRatio > methodology.targetLeverageRatio && _currentLeverageRatio <= twapLeverageRatio) ); } /** * Calculate the current leverage ratio given a valuation of the collateral and borrow asset, which is calculated as collateral USD valuation / SetToken USD valuation * * return uint256 Current leverage ratio */ function _calculateCurrentLeverageRatio( uint256 _collateralValue, uint256 _borrowValue ) internal pure returns(uint256) { return _collateralValue.preciseDiv(_collateralValue.sub(_borrowValue)); } /** * Calculate the new leverage ratio using the flexible leverage methodology. The methodology reduces the size of each rebalance by weighting * the current leverage ratio against the target leverage ratio by the recentering speed percentage. The lower the recentering speed, the slower * the leverage token will move towards the target leverage each rebalance. * * return uint256 New leverage ratio based on the flexible leverage methodology */ function _calculateNewLeverageRatio(uint256 _currentLeverageRatio) internal view returns(uint256) { // CLRt+1 = max(MINLR, min(MAXLR, CLRt * (1 - RS) + TLR * RS)) // a: TLR * RS // b: (1- RS) * CLRt // c: (1- RS) * CLRt + TLR * RS // d: min(MAXLR, CLRt * (1 - RS) + TLR * RS) uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed); uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio); uint256 c = a.add(b); uint256 d = Math.min(c, methodology.maxLeverageRatio); return Math.max(methodology.minLeverageRatio, d); } /** * Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units. * * return uint256 Chunked rebalance notional in collateral units * return uint256 Total rebalance notional in collateral units */ function _calculateChunkRebalanceNotional( LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio, bool _isLever ) internal view returns (uint256, uint256) { // Calculate absolute value of difference between new and current leverage ratio uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio); uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance); uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever); uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize); return (chunkRebalanceNotional, totalRebalanceNotional); } /** * Calculate the max borrow / repay amount allowed in collateral units for lever / delever. This is due to overcollateralization requirements on * assets deposited in lending protocols for borrowing. * * For lever, max borrow is calculated as: * (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals * * For delever, max borrow is calculated as: * Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD * * Net borrow limit is calculated as: * The collateral value in USD * Compound collateral factor * (1 - unutilized leverage %) * * return uint256 Max borrow notional denominated in collateral asset */ function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) { // Retrieve collateral factor which is the % increase in borrow limit in precise units (75% = 75 * 1e16) ( , uint256 collateralFactorMantissa, ) = strategy.comptroller.markets(address(strategy.targetCollateralCToken)); uint256 netBorrowLimit = _actionInfo.collateralValue .preciseMul(collateralFactorMantissa) .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage)); if (_isLever) { return netBorrowLimit .sub(_actionInfo.borrowValue) .preciseDiv(_actionInfo.collateralPrice); } else { return _actionInfo.collateralBalance .preciseMul(netBorrowLimit.sub(_actionInfo.borrowValue)) .preciseDiv(netBorrowLimit); } } /** * Derive the borrow units for lever. The units are calculated by the collateral units multiplied by collateral / borrow asset price. Compound oracle prices * already adjust for decimals in the token. * * return uint256 Position units to borrow */ function _calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internal pure returns (uint256) { return _collateralRebalanceUnits.preciseMul(_actionInfo.collateralPrice).preciseDiv(_actionInfo.borrowPrice); } /** * Calculate the min receive units in collateral units for lever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance * * return uint256 Min position units to receive after lever trade */ function _calculateMinCollateralReceiveUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance) internal pure returns (uint256) { return _collateralRebalanceUnits.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance)); } /** * Derive the min repay units from collateral units for delever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance * and pair price (collateral oracle price / borrow oracle price). Compound oracle prices already adjust for decimals in the token. * * return uint256 Min position units to repay in borrow asset */ function _calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internal pure returns (uint256) { return _collateralRebalanceUnits .preciseMul(_actionInfo.collateralPrice) .preciseDiv(_actionInfo.borrowPrice) .preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance)); } /** * Update last trade timestamp and if chunk rebalance size is less than total rebalance notional, store new leverage ratio to kick off TWAP. Used in * the engage() and rebalance() functions */ function _updateRebalanceState( uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional, uint256 _newLeverageRatio ) internal { lastTradeTimestamp = block.timestamp; if (_chunkRebalanceNotional < _totalRebalanceNotional) { twapLeverageRatio = _newLeverageRatio; } } /** * Update last trade timestamp and if chunk rebalance size is equal to the total rebalance notional, end TWAP by clearing state. This function is used * in iterateRebalance() */ function _updateIterateState(uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional) internal { lastTradeTimestamp = block.timestamp; // If the chunk size is equal to the total notional meaning that rebalances are not chunked, then clear TWAP state. if (_chunkRebalanceNotional == _totalRebalanceNotional) { delete twapLeverageRatio; } } /** * Update last trade timestamp and if currently in a TWAP, delete the TWAP state. Used in the ripcord() function. */ function _updateRipcordState() internal { lastTradeTimestamp = block.timestamp; // If TWAP leverage ratio is stored, then clear state. This may happen if we are currently in a TWAP rebalance, and the leverage ratio moves above the // incentivized threshold for ripcord. if (twapLeverageRatio > 0) { delete twapLeverageRatio; } } /** * Transfer ETH reward to caller of the ripcord function. If the ETH balance on this contract is less than required * incentive quantity, then transfer contract balance instead to prevent reverts. * * return uint256 Amount of ETH transferred to caller */ function _transferEtherRewardToCaller(uint256 _etherReward) internal returns(uint256) { uint256 etherToTransfer = _etherReward < address(this).balance ? _etherReward : address(this).balance; msg.sender.transfer(etherToTransfer); return etherToTransfer; } /** * Internal function returning the ShouldRebalance enum used in shouldRebalance and shouldRebalanceWithBounds external getter functions * * return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action */ function _shouldRebalance( uint256 _currentLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio ) internal view returns(ShouldRebalance) { // If above ripcord threshold, then check if incentivized cooldown period has elapsed if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) { if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) { return ShouldRebalance.RIPCORD; } } else { // If TWAP, then check if the cooldown period has elapsed if (twapLeverageRatio > 0) { if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) { return ShouldRebalance.ITERATE_REBALANCE; } } else { // If not TWAP, then check if the rebalance interval has elapsed OR current leverage is above max leverage OR current leverage is below // min leverage if ( block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval || _currentLeverageRatio > _maxLeverageRatio || _currentLeverageRatio < _minLeverageRatio ) { return ShouldRebalance.REBALANCE; } } } // If none of the above conditions are satisfied, then should not rebalance return ShouldRebalance.NONE; } } pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ICErc20 * * Interface for interacting with Compound cErc20 tokens (e.g. Dai, USDC) */ interface ICErc20 is IERC20 { function borrowBalanceCurrent(address _account) external returns (uint256); function borrowBalanceStored(address _account) external view returns (uint256); function balanceOfUnderlying(address _account) external returns (uint256); /** * Calculates the exchange rate from the underlying to the CToken * * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external view returns (address); /** * Sender supplies assets into the market and receives cTokens in exchange * * @notice Accrues interest whether or not the operation succeeds, unless reverted * @param _mintAmount The amount of the underlying asset to supply * @return uint256 0=success, otherwise a failure */ function mint(uint256 _mintAmount) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param _redeemTokens The number of cTokens to redeem into underlying * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 _redeemTokens) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param _redeemAmount The amount of underlying to redeem * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 _redeemAmount) external returns (uint256); /** * @notice Sender borrows assets from the protocol to their own address * @param _borrowAmount The amount of the underlying asset to borrow * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 _borrowAmount) external returns (uint256); /** * @notice Sender repays their own borrow * @param _repayAmount The amount to repay * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint256 _repayAmount) external returns (uint256); } pragma solidity 0.6.10; /** * @title ICompoundPriceOracle * * Interface for interacting with Compound price oracle */ interface ICompoundPriceOracle { function getUnderlyingPrice(address _asset) external view returns(uint256); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { FlexibleLeverageStrategyAdapter } from "../adapters/FlexibleLeverageStrategyAdapter.sol"; interface IFLIStrategyAdapter { function getStrategy() external view returns (FlexibleLeverageStrategyAdapter.ContractSettings memory); function getMethodology() external view returns (FlexibleLeverageStrategyAdapter.MethodologySettings memory); function getIncentive() external view returns (FlexibleLeverageStrategyAdapter.IncentiveSettings memory); function getExecution() external view returns (FlexibleLeverageStrategyAdapter.ExecutionSettings memory); function getCurrentLeverageRatio() external view returns (uint256); function shouldRebalance() external view returns (FlexibleLeverageStrategyAdapter.ShouldRebalance); function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(FlexibleLeverageStrategyAdapter.ShouldRebalance); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IUniswapV2Router { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function 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); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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); } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; import { IBaseManager } from "../interfaces/IBaseManager.sol"; /** * @title BaseAdapter * @author Set Protocol * * Abstract class that houses common adapter-related state and functions. */ abstract contract BaseAdapter { using AddressArrayUtils for address[]; /* ============ Events ============ */ event CallerStatusUpdated(address indexed _caller, bool _status); event AnyoneCallableUpdated(bool indexed _status); /* ============ Modifiers ============ */ /** * Throws if the sender is not the SetToken operator */ modifier onlyOperator() { require(msg.sender == manager.operator(), "Must be operator"); _; } /** * Throws if the sender is not the SetToken methodologist */ modifier onlyMethodologist() { require(msg.sender == manager.methodologist(), "Must be methodologist"); _; } /** * Throws if caller is a contract, can be used to stop flash loan and sandwich attacks */ modifier onlyEOA() { require(msg.sender == tx.origin, "Caller must be EOA Address"); _; } /** * Throws if not allowed caller */ modifier onlyAllowedCaller(address _caller) { require(isAllowedCaller(_caller), "Address not permitted to call"); _; } /* ============ State Variables ============ */ // Instance of manager contract IBaseManager public manager; // Boolean indicating if anyone can call function bool public anyoneCallable; // Mapping of addresses allowed to call function mapping(address => bool) public callAllowList; /* ============ Constructor ============ */ constructor(IBaseManager _manager) public { manager = _manager; } /* ============ External Functions ============ */ /** * OPERATOR ONLY: Toggle ability for passed addresses to call only allowed caller functions * * @param _callers Array of caller addresses to toggle status * @param _statuses Array of statuses for each caller */ function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator { require(_callers.length == _statuses.length, "Array length mismatch"); require(_callers.length > 0, "Array length must be > 0"); require(!_callers.hasDuplicate(), "Cannot duplicate callers"); for (uint256 i = 0; i < _callers.length; i++) { address caller = _callers[i]; bool status = _statuses[i]; callAllowList[caller] = status; emit CallerStatusUpdated(caller, status); } } /** * OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist * * @param _status Boolean indicating whether to allow anyone call */ function updateAnyoneCallable(bool _status) external onlyOperator { anyoneCallable = _status; emit AnyoneCallableUpdated(_status); } /* ============ Internal Functions ============ */ /** * Invoke manager to transfer tokens from manager to other contract. * * @param _token Token being transferred from manager contract * @param _amount Amount of token being transferred */ function invokeManagerTransfer(address _token, address _destination, uint256 _amount) internal { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _destination, _amount); invokeManager(_token, callData); } /** * Invoke call from manager * * @param _module Module to interact with * @param _encoded Encoded byte data */ function invokeManager(address _module, bytes memory _encoded) internal { manager.interactManager(_module, _encoded); } /** * Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved. * * return bool Boolean indicating if allowed caller */ function isAllowedCaller(address _caller) internal view virtual returns (bool) { return anyoneCallable || callAllowList[_caller]; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "./ISetToken.sol"; interface IBaseManager { function setToken() external returns(ISetToken); function methodologist() external returns(address); function operator() external returns(address); function interactManager(address _module, bytes calldata _encoded) external; } pragma solidity 0.6.10; /** * @title IComptroller * * Interface for interacting with Compound Comptroller */ interface IComptroller { /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) external returns (uint256[] memory); /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint256); function claimComp(address holder) external; function markets(address cTokenAddress) external view returns (bool, uint256, bool); } pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "./ISetToken.sol"; interface ICompoundLeverageModule { function sync( ISetToken _setToken ) external; function lever( ISetToken _setToken, address _borrowAsset, address _collateralAsset, uint256 _borrowQuantity, uint256 _minReceiveQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external; function delever( ISetToken _setToken, address _collateralAsset, address _repayAsset, uint256 _redeemQuantity, uint256 _minRepayQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external; function gulp( ISetToken _setToken, address _collateralAsset, uint256 _minNotionalReceiveQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external; } pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } }
* @title FlexibleLeverageStrategyAdapter @author Set Protocol Smart contract that enables trustless leverage tokens using the flexible leverage methodology. This adapter is paired with the CompoundLeverageModule from Set protocol where module interactions are invoked via the IBaseManager contract. Any leveraged token can be constructed as long as the collateral and borrow asset is available on Compound. This adapter contract also allows the operator to set an ETH reward to incentivize keepers calling the rebalance function at different leverage thresholds./
contract FlexibleLeverageStrategyAdapter is BaseAdapter { using Address for address; using PreciseUnitMath for uint256; using SafeMath for uint256; Copyright 2021 Set Labs Inc. import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { Math } from "@openzeppelin/contracts/math/Math.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { BaseAdapter } from "../lib/BaseAdapter.sol"; import { ICErc20 } from "../interfaces/ICErc20.sol"; import { IBaseManager } from "../interfaces/IBaseManager.sol"; import { IComptroller } from "../interfaces/IComptroller.sol"; import { ICompoundLeverageModule } from "../interfaces/ICompoundLeverageModule.sol"; import { ICompoundPriceOracle } from "../interfaces/ICompoundPriceOracle.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; enum ShouldRebalance { } struct ActionInfo { } struct LeverageInfo { ActionInfo action; } struct ContractSettings { } struct MethodologySettings { } struct ExecutionSettings { } struct IncentiveSettings { } event Engaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional); event Rebalanced( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional ); event RebalanceIterated( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional ); event RipcordCalled( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _rebalanceNotional, uint256 _etherIncentive ); event Disengaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional); event MethodologySettingsUpdated( uint256 _targetLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio, uint256 _recenteringSpeed, uint256 _rebalanceInterval ); event ExecutionSettingsUpdated( uint256 _unutilizedLeveragePercentage, uint256 _twapMaxTradeSize, uint256 _twapCooldownPeriod, uint256 _slippageTolerance, string _exchangeName, bytes _exchangeData ); event IncentiveSettingsUpdated( uint256 _etherReward, uint256 _incentivizedLeverageRatio, uint256 _incentivizedSlippageTolerance, uint256 _incentivizedTwapCooldownPeriod, uint256 _incentivizedTwapMaxTradeSize ); modifier noRebalanceInProgress() { require(twapLeverageRatio == 0, "Rebalance is currently in progress"); _; } IBaseManager _manager, ContractSettings memory _strategy, MethodologySettings memory _methodology, ExecutionSettings memory _execution, IncentiveSettings memory _incentive ) public BaseAdapter(_manager) constructor( { strategy = _strategy; methodology = _methodology; execution = _execution; incentive = _incentive; _validateSettings(methodology, execution, incentive); } function engage() external onlyOperator { ActionInfo memory engageInfo = _createActionInfo(); require(engageInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(engageInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(engageInfo.borrowBalance == 0, "Debt must be 0"); LeverageInfo memory leverageInfo = LeverageInfo({ action: engageInfo, slippageTolerance: execution.slippageTolerance, twapMaxTradeSize: execution.twapMaxTradeSize }); uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true); _lever(leverageInfo, chunkRebalanceNotional); _updateRebalanceState( chunkRebalanceNotional, totalRebalanceNotional, methodology.targetLeverageRatio ); emit Engaged( leverageInfo.currentLeverageRatio, methodology.targetLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } function engage() external onlyOperator { ActionInfo memory engageInfo = _createActionInfo(); require(engageInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(engageInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(engageInfo.borrowBalance == 0, "Debt must be 0"); LeverageInfo memory leverageInfo = LeverageInfo({ action: engageInfo, slippageTolerance: execution.slippageTolerance, twapMaxTradeSize: execution.twapMaxTradeSize }); uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true); _lever(leverageInfo, chunkRebalanceNotional); _updateRebalanceState( chunkRebalanceNotional, totalRebalanceNotional, methodology.targetLeverageRatio ); emit Engaged( leverageInfo.currentLeverageRatio, methodology.targetLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } ( function rebalance() external onlyEOA onlyAllowedCaller(msg.sender) { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); _validateNormalRebalance(leverageInfo, methodology.rebalanceInterval); _validateNonTWAP(); uint256 newLeverageRatio = _calculateNewLeverageRatio(leverageInfo.currentLeverageRatio); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _handleRebalance(leverageInfo, newLeverageRatio); _updateRebalanceState(chunkRebalanceNotional, totalRebalanceNotional, newLeverageRatio); emit Rebalanced( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } function iterateRebalance() external onlyEOA onlyAllowedCaller(msg.sender) { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); _validateNormalRebalance(leverageInfo, execution.twapCooldownPeriod); _validateTWAP(); uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (!_isAdvantageousTWAP(leverageInfo.currentLeverageRatio)) { (chunkRebalanceNotional, totalRebalanceNotional) = _handleRebalance(leverageInfo, twapLeverageRatio); } emit RebalanceIterated( leverageInfo.currentLeverageRatio, twapLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } function iterateRebalance() external onlyEOA onlyAllowedCaller(msg.sender) { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); _validateNormalRebalance(leverageInfo, execution.twapCooldownPeriod); _validateTWAP(); uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (!_isAdvantageousTWAP(leverageInfo.currentLeverageRatio)) { (chunkRebalanceNotional, totalRebalanceNotional) = _handleRebalance(leverageInfo, twapLeverageRatio); } emit RebalanceIterated( leverageInfo.currentLeverageRatio, twapLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } _updateIterateState(chunkRebalanceNotional, totalRebalanceNotional); function ripcord() external onlyEOA { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo( incentive.incentivizedSlippageTolerance, incentive.incentivizedTwapMaxTradeSize ); _validateRipcord(leverageInfo); ( uint256 chunkRebalanceNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.maxLeverageRatio, false); _delever(leverageInfo, chunkRebalanceNotional); _updateRipcordState(); uint256 etherTransferred = _transferEtherRewardToCaller(incentive.etherReward); emit RipcordCalled( leverageInfo.currentLeverageRatio, methodology.maxLeverageRatio, chunkRebalanceNotional, etherTransferred ); } function disengage() external onlyOperator { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); uint256 newLeverageRatio = PreciseUnitMath.preciseUnit(); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false); if (totalRebalanceNotional > chunkRebalanceNotional) { _delever(leverageInfo, chunkRebalanceNotional); _deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional); } emit Disengaged( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } function disengage() external onlyOperator { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); uint256 newLeverageRatio = PreciseUnitMath.preciseUnit(); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false); if (totalRebalanceNotional > chunkRebalanceNotional) { _delever(leverageInfo, chunkRebalanceNotional); _deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional); } emit Disengaged( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } } else { function setMethodologySettings(MethodologySettings memory _newMethodologySettings) external onlyOperator noRebalanceInProgress { methodology = _newMethodologySettings; _validateSettings(methodology, execution, incentive); emit MethodologySettingsUpdated( methodology.targetLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio, methodology.recenteringSpeed, methodology.rebalanceInterval ); } function setExecutionSettings(ExecutionSettings memory _newExecutionSettings) external onlyOperator noRebalanceInProgress { execution = _newExecutionSettings; _validateSettings(methodology, execution, incentive); emit ExecutionSettingsUpdated( execution.unutilizedLeveragePercentage, execution.twapMaxTradeSize, execution.twapCooldownPeriod, execution.slippageTolerance, execution.exchangeName, execution.exchangeData ); } function setIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) external onlyOperator noRebalanceInProgress { incentive = _newIncentiveSettings; _validateSettings(methodology, execution, incentive); emit IncentiveSettingsUpdated( incentive.etherReward, incentive.incentivizedLeverageRatio, incentive.incentivizedSlippageTolerance, incentive.incentivizedTwapCooldownPeriod, incentive.incentivizedTwapMaxTradeSize ); } function withdrawEtherBalance() external onlyOperator noRebalanceInProgress { msg.sender.transfer(address(this).balance); } receive() external payable {} function getCurrentLeverageRatio() public view returns(uint256) { ActionInfo memory currentLeverageInfo = _createActionInfo(); return _calculateCurrentLeverageRatio(currentLeverageInfo.collateralValue, currentLeverageInfo.borrowValue); } function getCurrentEtherIncentive() external view returns(uint256) { uint256 currentLeverageRatio = getCurrentLeverageRatio(); if (currentLeverageRatio >= incentive.incentivizedLeverageRatio) { return incentive.etherReward < address(this).balance ? incentive.etherReward : address(this).balance; return 0; } } function getCurrentEtherIncentive() external view returns(uint256) { uint256 currentLeverageRatio = getCurrentLeverageRatio(); if (currentLeverageRatio >= incentive.incentivizedLeverageRatio) { return incentive.etherReward < address(this).balance ? incentive.etherReward : address(this).balance; return 0; } } } else { function shouldRebalance() external view returns(ShouldRebalance) { uint256 currentLeverageRatio = getCurrentLeverageRatio(); return _shouldRebalance(currentLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio); } function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(ShouldRebalance) { require ( _customMinLeverageRatio <= methodology.minLeverageRatio && _customMaxLeverageRatio >= methodology.maxLeverageRatio, "Custom bounds must be valid" ); uint256 currentLeverageRatio = getCurrentLeverageRatio(); return _shouldRebalance(currentLeverageRatio, _customMinLeverageRatio, _customMaxLeverageRatio); } function getStrategy() external view returns (ContractSettings memory) { return strategy; } function getMethodology() external view returns (MethodologySettings memory) { return methodology; } function getExecution() external view returns (ExecutionSettings memory) { return execution; } function getIncentive() external view returns (IncentiveSettings memory) { return incentive; } function _lever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action); uint256 minReceiveCollateralUnits = _calculateMinCollateralReceiveUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance); bytes memory leverCallData = abi.encodeWithSignature( "lever(address,address,address,uint256,uint256,string,bytes)", address(strategy.setToken), strategy.borrowAsset, strategy.collateralAsset, borrowUnits, minReceiveCollateralUnits, execution.exchangeName, execution.exchangeData ); invokeManager(address(strategy.leverageModule), leverCallData); } function _delever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 minRepayUnits = _calculateMinRepayUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance, _leverageInfo.action); bytes memory deleverCallData = abi.encodeWithSignature( "delever(address,address,address,uint256,uint256,string,bytes)", address(strategy.setToken), strategy.collateralAsset, strategy.borrowAsset, collateralRebalanceUnits, minRepayUnits, execution.exchangeName, execution.exchangeData ); invokeManager(address(strategy.leverageModule), deleverCallData); } function _deleverToZeroBorrowBalance( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 maxCollateralRebalanceUnits = _chunkRebalanceNotional .preciseMul(PreciseUnitMath.preciseUnit().add(execution.slippageTolerance)) .preciseDiv(_leverageInfo.action.setTotalSupply); bytes memory deleverToZeroBorrowBalanceCallData = abi.encodeWithSignature( "deleverToZeroBorrowBalance(address,address,address,uint256,string,bytes)", address(strategy.setToken), strategy.collateralAsset, strategy.borrowAsset, maxCollateralRebalanceUnits, execution.exchangeName, execution.exchangeData ); invokeManager(address(strategy.leverageModule), deleverToZeroBorrowBalanceCallData); } function _handleRebalance(LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio) internal returns(uint256, uint256) { uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (_newLeverageRatio < _leverageInfo.currentLeverageRatio) { ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, false); _delever(_leverageInfo, chunkRebalanceNotional); ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, true); _lever(_leverageInfo, chunkRebalanceNotional); } return (chunkRebalanceNotional, totalRebalanceNotional); } function _handleRebalance(LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio) internal returns(uint256, uint256) { uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (_newLeverageRatio < _leverageInfo.currentLeverageRatio) { ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, false); _delever(_leverageInfo, chunkRebalanceNotional); ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, true); _lever(_leverageInfo, chunkRebalanceNotional); } return (chunkRebalanceNotional, totalRebalanceNotional); } } else { function _getAndValidateLeveragedInfo(uint256 _slippageTolerance, uint256 _maxTradeSize) internal view returns(LeverageInfo memory) { ActionInfo memory actionInfo = _createActionInfo(); require(actionInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(actionInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(actionInfo.borrowBalance > 0, "Borrow balance must exist"); uint256 currentLeverageRatio = _calculateCurrentLeverageRatio( actionInfo.collateralValue, actionInfo.borrowValue ); return LeverageInfo({ action: actionInfo, currentLeverageRatio: currentLeverageRatio, slippageTolerance: _slippageTolerance, twapMaxTradeSize: _maxTradeSize }); } function _getAndValidateLeveragedInfo(uint256 _slippageTolerance, uint256 _maxTradeSize) internal view returns(LeverageInfo memory) { ActionInfo memory actionInfo = _createActionInfo(); require(actionInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(actionInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(actionInfo.borrowBalance > 0, "Borrow balance must exist"); uint256 currentLeverageRatio = _calculateCurrentLeverageRatio( actionInfo.collateralValue, actionInfo.borrowValue ); return LeverageInfo({ action: actionInfo, currentLeverageRatio: currentLeverageRatio, slippageTolerance: _slippageTolerance, twapMaxTradeSize: _maxTradeSize }); } function _createActionInfo() internal view returns(ActionInfo memory) { ActionInfo memory rebalanceInfo; rebalanceInfo.collateralPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetCollateralCToken)); rebalanceInfo.borrowPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetBorrowCToken)); uint256 cTokenBalance = strategy.targetCollateralCToken.balanceOf(address(strategy.setToken)); rebalanceInfo.collateralBalance = cTokenBalance.preciseMul(strategy.targetCollateralCToken.exchangeRateStored()); rebalanceInfo.borrowBalance = strategy.targetBorrowCToken.borrowBalanceStored(address(strategy.setToken)); rebalanceInfo.collateralValue = rebalanceInfo.collateralPrice.preciseMul(rebalanceInfo.collateralBalance); rebalanceInfo.borrowValue = rebalanceInfo.borrowPrice.preciseMul(rebalanceInfo.borrowBalance); rebalanceInfo.setTotalSupply = strategy.setToken.totalSupply(); return rebalanceInfo; } function _validateSettings( MethodologySettings memory _methodology, ExecutionSettings memory _execution, IncentiveSettings memory _incentive ) internal pure { require ( _methodology.minLeverageRatio <= _methodology.targetLeverageRatio && _methodology.minLeverageRatio > 0, "Must be valid min leverage" ); require ( _methodology.maxLeverageRatio >= _methodology.targetLeverageRatio, "Must be valid max leverage" ); require ( _methodology.recenteringSpeed <= PreciseUnitMath.preciseUnit() && _methodology.recenteringSpeed > 0, "Must be valid recentering speed" ); require ( _execution.unutilizedLeveragePercentage <= PreciseUnitMath.preciseUnit(), "Unutilized leverage must be <100%" ); require ( _execution.slippageTolerance <= PreciseUnitMath.preciseUnit(), "Slippage tolerance must be <100%" ); require ( _incentive.incentivizedSlippageTolerance <= PreciseUnitMath.preciseUnit(), "Incentivized slippage tolerance must be <100%" ); require ( _incentive.incentivizedLeverageRatio >= _methodology.maxLeverageRatio, "Incentivized leverage ratio must be > max leverage ratio" ); require ( _methodology.rebalanceInterval >= _execution.twapCooldownPeriod, "Rebalance interval must be greater than TWAP cooldown period" ); require ( _execution.twapCooldownPeriod >= _incentive.incentivizedTwapCooldownPeriod, "TWAP cooldown must be greater than incentivized TWAP cooldown" ); require ( _execution.twapMaxTradeSize <= _incentive.incentivizedTwapMaxTradeSize, "TWAP max trade size must be less than incentivized TWAP max trade size" ); } function _validateNormalRebalance(LeverageInfo memory _leverageInfo, uint256 _coolDown) internal view { require(_leverageInfo.currentLeverageRatio < incentive.incentivizedLeverageRatio, "Must be below incentivized leverage ratio"); require( block.timestamp.sub(lastTradeTimestamp) > _coolDown || _leverageInfo.currentLeverageRatio > methodology.maxLeverageRatio || _leverageInfo.currentLeverageRatio < methodology.minLeverageRatio, "Cooldown not elapsed or not valid leverage ratio" ); } function _validateRipcord(LeverageInfo memory _leverageInfo) internal view { require(_leverageInfo.currentLeverageRatio >= incentive.incentivizedLeverageRatio, "Must be above incentivized leverage ratio"); require(lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp, "TWAP cooldown must have elapsed"); } function _validateTWAP() internal view { require(twapLeverageRatio > 0, "Not in TWAP state"); } function _validateNonTWAP() internal view { require(twapLeverageRatio == 0, "Must call iterate"); } function _isAdvantageousTWAP(uint256 _currentLeverageRatio) internal view returns (bool) { return ( (twapLeverageRatio < methodology.targetLeverageRatio && _currentLeverageRatio >= twapLeverageRatio) || (twapLeverageRatio > methodology.targetLeverageRatio && _currentLeverageRatio <= twapLeverageRatio) ); } function _calculateCurrentLeverageRatio( uint256 _collateralValue, uint256 _borrowValue ) internal pure returns(uint256) { return _collateralValue.preciseDiv(_collateralValue.sub(_borrowValue)); } function _calculateNewLeverageRatio(uint256 _currentLeverageRatio) internal view returns(uint256) { uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed); uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio); uint256 c = a.add(b); uint256 d = Math.min(c, methodology.maxLeverageRatio); return Math.max(methodology.minLeverageRatio, d); } function _calculateChunkRebalanceNotional( LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio, bool _isLever ) internal view returns (uint256, uint256) { uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio); uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance); uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever); uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize); return (chunkRebalanceNotional, totalRebalanceNotional); } function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) { ( , uint256 collateralFactorMantissa, ) = strategy.comptroller.markets(address(strategy.targetCollateralCToken)); uint256 netBorrowLimit = _actionInfo.collateralValue .preciseMul(collateralFactorMantissa) .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage)); if (_isLever) { return netBorrowLimit .sub(_actionInfo.borrowValue) .preciseDiv(_actionInfo.collateralPrice); return _actionInfo.collateralBalance .preciseMul(netBorrowLimit.sub(_actionInfo.borrowValue)) .preciseDiv(netBorrowLimit); } } function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) { ( , uint256 collateralFactorMantissa, ) = strategy.comptroller.markets(address(strategy.targetCollateralCToken)); uint256 netBorrowLimit = _actionInfo.collateralValue .preciseMul(collateralFactorMantissa) .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage)); if (_isLever) { return netBorrowLimit .sub(_actionInfo.borrowValue) .preciseDiv(_actionInfo.collateralPrice); return _actionInfo.collateralBalance .preciseMul(netBorrowLimit.sub(_actionInfo.borrowValue)) .preciseDiv(netBorrowLimit); } } } else { function _calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internal pure returns (uint256) { return _collateralRebalanceUnits.preciseMul(_actionInfo.collateralPrice).preciseDiv(_actionInfo.borrowPrice); } function _calculateMinCollateralReceiveUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance) internal pure returns (uint256) { return _collateralRebalanceUnits.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance)); } function _calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internal pure returns (uint256) { return _collateralRebalanceUnits .preciseMul(_actionInfo.collateralPrice) .preciseDiv(_actionInfo.borrowPrice) .preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance)); } function _updateRebalanceState( uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional, uint256 _newLeverageRatio ) internal { lastTradeTimestamp = block.timestamp; if (_chunkRebalanceNotional < _totalRebalanceNotional) { twapLeverageRatio = _newLeverageRatio; } } function _updateRebalanceState( uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional, uint256 _newLeverageRatio ) internal { lastTradeTimestamp = block.timestamp; if (_chunkRebalanceNotional < _totalRebalanceNotional) { twapLeverageRatio = _newLeverageRatio; } } function _updateIterateState(uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional) internal { lastTradeTimestamp = block.timestamp; if (_chunkRebalanceNotional == _totalRebalanceNotional) { delete twapLeverageRatio; } } function _updateIterateState(uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional) internal { lastTradeTimestamp = block.timestamp; if (_chunkRebalanceNotional == _totalRebalanceNotional) { delete twapLeverageRatio; } } function _updateRipcordState() internal { lastTradeTimestamp = block.timestamp; if (twapLeverageRatio > 0) { delete twapLeverageRatio; } } function _updateRipcordState() internal { lastTradeTimestamp = block.timestamp; if (twapLeverageRatio > 0) { delete twapLeverageRatio; } } function _transferEtherRewardToCaller(uint256 _etherReward) internal returns(uint256) { uint256 etherToTransfer = _etherReward < address(this).balance ? _etherReward : address(this).balance; msg.sender.transfer(etherToTransfer); return etherToTransfer; } function _shouldRebalance( uint256 _currentLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio ) internal view returns(ShouldRebalance) { if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) { if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) { return ShouldRebalance.RIPCORD; } if (twapLeverageRatio > 0) { if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) { return ShouldRebalance.ITERATE_REBALANCE; } block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval || _currentLeverageRatio > _maxLeverageRatio || _currentLeverageRatio < _minLeverageRatio ) { return ShouldRebalance.REBALANCE; } } } } function _shouldRebalance( uint256 _currentLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio ) internal view returns(ShouldRebalance) { if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) { if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) { return ShouldRebalance.RIPCORD; } if (twapLeverageRatio > 0) { if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) { return ShouldRebalance.ITERATE_REBALANCE; } block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval || _currentLeverageRatio > _maxLeverageRatio || _currentLeverageRatio < _minLeverageRatio ) { return ShouldRebalance.REBALANCE; } } } } function _shouldRebalance( uint256 _currentLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio ) internal view returns(ShouldRebalance) { if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) { if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) { return ShouldRebalance.RIPCORD; } if (twapLeverageRatio > 0) { if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) { return ShouldRebalance.ITERATE_REBALANCE; } block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval || _currentLeverageRatio > _maxLeverageRatio || _currentLeverageRatio < _minLeverageRatio ) { return ShouldRebalance.REBALANCE; } } } } } else { function _shouldRebalance( uint256 _currentLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio ) internal view returns(ShouldRebalance) { if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) { if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) { return ShouldRebalance.RIPCORD; } if (twapLeverageRatio > 0) { if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) { return ShouldRebalance.ITERATE_REBALANCE; } block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval || _currentLeverageRatio > _maxLeverageRatio || _currentLeverageRatio < _minLeverageRatio ) { return ShouldRebalance.REBALANCE; } } } } function _shouldRebalance( uint256 _currentLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio ) internal view returns(ShouldRebalance) { if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) { if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) { return ShouldRebalance.RIPCORD; } if (twapLeverageRatio > 0) { if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) { return ShouldRebalance.ITERATE_REBALANCE; } block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval || _currentLeverageRatio > _maxLeverageRatio || _currentLeverageRatio < _minLeverageRatio ) { return ShouldRebalance.REBALANCE; } } } } } else { if ( function _shouldRebalance( uint256 _currentLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio ) internal view returns(ShouldRebalance) { if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) { if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) { return ShouldRebalance.RIPCORD; } if (twapLeverageRatio > 0) { if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) { return ShouldRebalance.ITERATE_REBALANCE; } block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval || _currentLeverageRatio > _maxLeverageRatio || _currentLeverageRatio < _minLeverageRatio ) { return ShouldRebalance.REBALANCE; } } } } return ShouldRebalance.NONE; }
13,571,981
[ 1, 19667, 1523, 1682, 5682, 4525, 4216, 225, 1000, 4547, 19656, 6835, 716, 19808, 10267, 2656, 884, 5682, 2430, 1450, 326, 16600, 1523, 884, 5682, 707, 4676, 18, 1220, 4516, 353, 18066, 598, 326, 21327, 1682, 5682, 3120, 628, 1000, 1771, 1625, 1605, 23877, 854, 8187, 3970, 326, 467, 2171, 1318, 6835, 18, 5502, 884, 502, 11349, 1147, 848, 506, 15688, 487, 1525, 487, 326, 4508, 2045, 287, 471, 29759, 3310, 353, 2319, 603, 21327, 18, 1220, 4516, 6835, 2546, 5360, 326, 3726, 358, 444, 392, 512, 2455, 19890, 358, 316, 2998, 427, 554, 3455, 414, 4440, 326, 283, 12296, 445, 622, 3775, 884, 5682, 19983, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 478, 21873, 1682, 5682, 4525, 4216, 353, 3360, 4216, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 2962, 30708, 2802, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 25417, 26599, 21, 1000, 511, 5113, 15090, 18, 203, 203, 5666, 288, 5267, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 1887, 18, 18281, 14432, 203, 5666, 288, 4232, 39, 3462, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 3462, 19, 654, 39, 3462, 18, 18281, 14432, 203, 5666, 288, 2361, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 15949, 19, 10477, 18, 18281, 14432, 203, 5666, 288, 14060, 10477, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 15949, 19, 9890, 10477, 18, 18281, 14432, 203, 5666, 288, 3360, 4216, 289, 628, 315, 6216, 2941, 19, 2171, 4216, 18, 18281, 14432, 203, 5666, 288, 467, 1441, 1310, 3462, 289, 628, 315, 6216, 15898, 19, 11774, 1310, 3462, 18, 18281, 14432, 203, 5666, 288, 467, 2171, 1318, 289, 628, 315, 6216, 15898, 19, 45, 2171, 1318, 18, 18281, 14432, 203, 5666, 288, 467, 799, 337, 1539, 289, 628, 315, 6216, 15898, 19, 45, 799, 337, 1539, 18, 18281, 14432, 203, 5666, 288, 467, 16835, 1682, 5682, 3120, 289, 628, 315, 6216, 15898, 19, 45, 16835, 1682, 5682, 3120, 18, 18281, 14432, 203, 5666, 288, 467, 16835, 5147, 2 ]
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; contract BTRST { /// @notice EIP-20 token name for this token string public constant name = "BTRST"; /// @notice EIP-20 token symbol for this token string public constant symbol = "BTRST"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 250000000e18; // 250 million BTRST /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new BTRST token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "BTRST::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "BTRST::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "BTRST::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "BTRST::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "BTRST::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "BTRST::delegateBySig: invalid nonce"); require(now <= expiry, "BTRST::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "BTRST::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "BTRST::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "BTRST::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "BTRST::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "BTRST::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "BTRST::_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, "BTRST::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "BTRST::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function 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; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @notice Determine the prior number of votes for an account as of a block number @dev Block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address of the account to check @param blockNumber The block number to get the vote balance at @return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "BTRST::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
6,694,448
[ 1, 8519, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 225, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 225, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 225, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 327, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 19, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 1203, 1854, 13, 1071, 1476, 1135, 261, 11890, 10525, 13, 288, 203, 3639, 2583, 12, 2629, 1854, 411, 1203, 18, 2696, 16, 315, 38, 4349, 882, 2866, 588, 25355, 29637, 30, 486, 4671, 11383, 8863, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 273, 374, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xd3DE4D2BafC8Ce8084767220103f954f844FEe85/sources/TheReplicants.sol
launch variables prevent more than 1 buy on same block this may cuz rug check bots to fail but helpful on launches exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract TheReplicants is ERC20, Ownable { IDexRouter public dexRouter; address public lpPair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; address public RouterAddress; address public LiquidityReceiver; uint256 public maxTxnAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public lpMarketingEnabled = false; uint256 public lpMarketingFrequency = 0 seconds; uint256 public lastLpMarketingTime; uint256 public manualMarketingFrequency = 1 hours; uint256 public lastManualLpMarketingTime; bool public tradingActive = false; uint256 private _blocks; uint256 public tradingActiveBlock = 0; bool public swapEnabled = false; bool public transferDelayEnabled = false; uint256 public TotalbuyFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public TotalsellFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedmaxTxnAmount; mapping (address => bool) public automatedMarketMakerPairs; event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(uint256 amount); event ManualNukeLP(uint256 amount); event OwnerForcedSwapBack(uint256 timestamp); constructor() ERC20("The Replicants", "$TR") payable { uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 5; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 5; uint256 totalSupply = 1e5 * 10 * 1e18; maxTxnAmount = totalSupply * 2 / 100; maxWallet = totalSupply * 2 / 100; swapTokensAtAmount = totalSupply * 1 / 1000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = 0; TotalbuyFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = 0; TotalsellFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); devWallet = address(owner()); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); marketingWallet=owner(); LiquidityReceiver=owner(); IDexRouter _dexRouter = IDexRouter(RouterAddress); dexRouter = _dexRouter; lastLpMarketingTime = block.timestamp; lpPair = IDexFactory(_dexRouter.factory()).createPair(address(this), _dexRouter.WETH()); excludeFromMaxTransaction(address(lpPair), true); _setAutomatedMarketMakerPair(address(lpPair), true); _createInitialSupply(owner(), totalSupply*100/100); } mapping (address => bool) private _isBlackListed; receive() external payable {} function DisableTransferDelay() external onlyOwner { transferDelayEnabled = false; } function setSwapTokensAt(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxn_base1000(uint256 newNum) external onlyOwner { require(newNum >= 5, "Cannot set maxTxnAmount lower than 0.5%"); maxTxnAmount = ((totalSupply() * newNum / 1000)/1e18) * (10**18); } function updateMaxWallet_base1000(uint256 newNum) external onlyOwner { require(newNum >= 5, "Cannot set maxWallet lower than 0.5%"); maxWallet = ((totalSupply() * newNum / 1000)/1e18) * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedmaxTxnAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _setbuyfees(uint256 _marketing,uint256 _liquidity) external onlyOwner{ require((_marketing+_liquidity) <= 30, "Must keep fees lower than 30%"); buyMarketingFee = _marketing; buyLiquidityFee = _liquidity; TotalbuyFees = buyMarketingFee + buyLiquidityFee; } function _setsellfees(uint256 _marketing,uint256 _liquidity) external onlyOwner{ require((_marketing+_liquidity) <= 30, "Must keep fees lower than 30%"); sellMarketingFee = _marketing; sellLiquidityFee = _liquidity; TotalsellFees = sellMarketingFee + sellLiquidityFee; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != lpPair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; } function SetupFeeReceivers(address _mar,address _liq,address _dev) external onlyOwner { marketingWallet = _mar; LiquidityReceiver = _liq; devWallet = _dev; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlackListed[to], "You have no power here!"); require(!_isBlackListed[tx.origin], "You have no power here!"); if(amount == 0) { super._transfer(from, to, 0); return; } if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping && !_isExcludedFromFees[to] && !_isExcludedFromFees[from] ){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferBlock[tx.origin] < block.number - 1 && _holderLastTransferBlock[to] < block.number - 1, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferBlock[tx.origin] = block.number; _holderLastTransferBlock[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedmaxTxnAmount[to]) { require(amount <= maxTxnAmount, "Buy transfer amount exceeds the maxTxnAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedmaxTxnAmount[from]) { require(amount <= maxTxnAmount, "Sell transfer amount exceeds the maxTxnAmount."); } else if (!_isExcludedmaxTxnAmount[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] && lpMarketingEnabled && block.timestamp >= lastLpMarketingTime + lpMarketingFrequency && !_isExcludedFromFees[from]){ autoMarketingLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if((tradingActiveBlock >= block.number - _blocks) && automatedMarketMakerPairs[from]){ fees = amount * 99 / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if (automatedMarketMakerPairs[to] && TotalsellFees > 0){ fees = amount * TotalsellFees / 100; tokensForLiquidity += fees * sellLiquidityFee / TotalsellFees; tokensForMarketing += fees * sellMarketingFee / TotalsellFees; tokensForDev += fees * sellDevFee / TotalsellFees; } else if(automatedMarketMakerPairs[from] && TotalbuyFees > 0) { fees = amount * TotalbuyFees / 100; tokensForLiquidity += fees * buyLiquidityFee / TotalbuyFees; tokensForMarketing += fees * buyMarketingFee / TotalbuyFees; tokensForDev += fees * buyDevFee / TotalbuyFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); _approve(address(this), address(dexRouter), tokenAmount); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(dexRouter), tokenAmount); address(this), tokenAmount, LiquidityReceiver, block.timestamp ); } dexRouter.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance - liquidityTokens; uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance - initialETHBalance; uint256 ethForMarketing = ethBalance * tokensForMarketing / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance - liquidityTokens; uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance - initialETHBalance; uint256 ethForMarketing = ethBalance * tokensForMarketing / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); (success,) = address(marketingWallet).call{value: ethForMarketing}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance - liquidityTokens; uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance - initialETHBalance; uint256 ethForMarketing = ethBalance * tokensForMarketing / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2)); 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 forceSwapBack() external onlyOwner { require(balanceOf(address(this)) >= swapTokensAtAmount, "Can only swap when token amount is at or higher than restriction"); swapping = true; swapBack(); swapping = false; emit OwnerForcedSwapBack(block.timestamp); } function autoMarketingLiquidityPairTokens() internal{ lastLpMarketingTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(lpPair); uint256 amountToMarketing = liquidityPairBalance * percentForLPMarketing / 10000; if (amountToMarketing > 0){ super._transfer(lpPair, address(0xdead), amountToMarketing); } pair.sync(); emit AutoNukeLP(amountToMarketing); } function autoMarketingLiquidityPairTokens() internal{ lastLpMarketingTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(lpPair); uint256 amountToMarketing = liquidityPairBalance * percentForLPMarketing / 10000; if (amountToMarketing > 0){ super._transfer(lpPair, address(0xdead), amountToMarketing); } pair.sync(); emit AutoNukeLP(amountToMarketing); } IDexPair pair = IDexPair(lpPair); function manualMarketingLiquidityPairTokens(uint256 percent) external onlyOwner { require(block.timestamp > lastManualLpMarketingTime + manualMarketingFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpMarketingTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(lpPair); uint256 amountToMarketing = liquidityPairBalance * percent / 10000; if (amountToMarketing > 0){ super._transfer(lpPair, address(0xdead), amountToMarketing); } pair.sync(); } function manualMarketingLiquidityPairTokens(uint256 percent) external onlyOwner { require(block.timestamp > lastManualLpMarketingTime + manualMarketingFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpMarketingTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(lpPair); uint256 amountToMarketing = liquidityPairBalance * percent / 10000; if (amountToMarketing > 0){ super._transfer(lpPair, address(0xdead), amountToMarketing); } pair.sync(); } IDexPair pair = IDexPair(lpPair); function EnableTrading() external onlyOwner { require(!tradingActive, "Trading is already active, cannot relaunch."); tradingActive = true; swapEnabled = true; tradingActiveBlock = block.number; _blocks = 0; } function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; } (success,) = address(msg.sender).call{value: address(this).balance}(""); function isBot(address account) public view returns (bool) { return _isBlackListed[account]; } function _enieslobby(address[] memory Addresses,bool _status) external onlyOwner(){ for (uint256 i; i < Addresses.length; ++i) { if(Addresses[i] != lpPair && Addresses[i] != address(this)){ _isBlackListed[Addresses[i]] = _status; } } } function _enieslobby(address[] memory Addresses,bool _status) external onlyOwner(){ for (uint256 i; i < Addresses.length; ++i) { if(Addresses[i] != lpPair && Addresses[i] != address(this)){ _isBlackListed[Addresses[i]] = _status; } } } function _enieslobby(address[] memory Addresses,bool _status) external onlyOwner(){ for (uint256 i; i < Addresses.length; ++i) { if(Addresses[i] != lpPair && Addresses[i] != address(this)){ _isBlackListed[Addresses[i]] = _status; } } } }
4,451,041
[ 1, 20738, 3152, 5309, 1898, 2353, 404, 30143, 603, 1967, 1203, 333, 2026, 15985, 94, 436, 637, 866, 2512, 87, 358, 2321, 1496, 28063, 603, 8037, 281, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1021, 426, 1780, 4388, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 1599, 338, 8259, 1071, 302, 338, 8259, 31, 203, 565, 1758, 1071, 12423, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 565, 1758, 1071, 9703, 1887, 31, 203, 565, 1758, 1071, 511, 18988, 24237, 12952, 31, 203, 377, 203, 27699, 377, 203, 203, 565, 2254, 5034, 1071, 943, 13789, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 203, 377, 203, 565, 1426, 1071, 12423, 3882, 21747, 1526, 273, 629, 31, 203, 565, 2254, 5034, 1071, 12423, 3882, 21747, 13865, 273, 374, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 3882, 21747, 950, 31, 203, 565, 2254, 5034, 1071, 11297, 3882, 21747, 13865, 273, 404, 7507, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 3882, 21747, 950, 31, 203, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 2254, 5034, 3238, 389, 7996, 31, 203, 565, 2254, 5034, 1071, 1284, 7459, 3896, 1768, 273, 374, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 377, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 629, 31, 203, 203, 565, 2254, 5034, 1071, 10710, 70, 9835, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-03-12 */ // SPDX-License-Identifier: Unlicensed /** _______ _____ _ _ __ __ _____ _____ _ _ _ _ |__ __| __ \| | | | \/ | __ \_ _| \ | | | | | | | | |__) | | | | \ / | |__) || | | \| | | | | | | | _ /| | | | |\/| | ___/ | | | . ` | | | | | | | | \ \| |__| | | | | | _| |_| |\ | |__| | |_| |_| \_\\____/|_| |_|_| |_____|_| \_|\____/ Buy tax 10% / Sell tax 12% */ pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract TrumpInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public earlySellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Trump Inu", "$TRUMP") { 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 = 5; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 7; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 2; uint256 _earlySellLiquidityFee = 2; uint256 _earlySellMarketingFee = 5; uint256 _earlySellDevFee = 5 ; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 20 / 1000; // 2% maxWallet swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } // 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; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // 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"); } } } // anti bot logic if (block.number <= (launchedAt + 1) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } // early sell logic bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } else { sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if 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 address(this), 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 Chire(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract TrumpInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; mapping (address => uint256) private _holderFirstBuyTimestamp; mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public earlySellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; uint256 launchedAt; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Trump Inu", "$TRUMP") { 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 = 5; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 7; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 2; uint256 _earlySellLiquidityFee = 2; uint256 _earlySellMarketingFee = 5; uint256 _earlySellDevFee = 5 ; uint256 totalSupply = 1 * 1e12 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 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; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if (block.number <= (launchedAt + 1) && function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } bool isBuy = from == uniswapV2Pair; function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else { } else { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 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); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); function Chire(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } function Chire(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
15,034,674
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4352, 749, 1635, 22467, 1098, 1635, 1203, 1300, 434, 10191, 1284, 7459, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 840, 2801, 382, 89, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 7010, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 7010, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 565, 1426, 1071, 4237, 41, 20279, 55, 1165, 7731, 273, 638, 31, 203, 7010, 7010, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3759, 38, 9835, 4921, 31, 203, 7010, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 22491, 31, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 7010, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 8870, 14667, 31, 203, 7010, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 2 ]
pragma solidity ^0.5.0; import "zeppelin/contracts/token/ERC721/ERC721Full.sol"; /// @title A trading platform for digital art /// @author Manank Patni /// @notice The contract create a platform for the digital art trading and showcase /// @dev The contract inherits ERC721 token to implement NFT contract Collectibles is ERC721Full { address payable public contract_owner; bool private stop = true; modifier contractOwner{ require(msg.sender == contract_owner); _; } modifier paidEnough(uint _price){ require(_price <= msg.value); _; } modifier onSale(uint id){ require(art_list[id].onsale == true); _; } modifier onlyOwner(uint id){ require(art_list[id].owner == msg.sender); _; } modifier stopFunctioning{ require(stop == true); _; } event AddArt(uint artid); event SwitchSaleStatus(uint artid, bool status); struct Art{ uint id; string name; string description; string image; address payable artist; uint price; address payable owner; bool onsale; } Art[] private art_list; /// @dev Makes the contract deployer as owner, set Token Symbol and Name constructor() ERC721Full("DigArt", "DAC") public { contract_owner = msg.sender; } /// @notice Owner can disable the app temporarily in case of emergency /// @dev Creates a circuit breaker in case of unprecedented bugs, switches on and off function switchContractWorking() public contractOwner{ if(stop == true){ stop = false; } else{ stop = true; } } /// @dev Returns the number total number of tokens /// @return count in integers function getartlength() public view returns (uint) { uint count = art_list.length; return count; } /// @dev Get a particular token by id /// @param id of token /// @return Returns id, name, description, image, artist, price, owner, onsaleornot function getArt(uint id) public view returns (uint, string memory, string memory, string memory, address, uint, address, bool) { Art memory a = art_list[id]; return (id, a.name, a.description, a.image, a.artist, a.price, a.owner, a.onsale); } /// @dev Convert a digital art to NFT /// @param name Name of the Token /// @param desc Short description of the collectibles /// @param image_url IPFS url of the image /// @param price Collectibe sell price /// @return id of minted token function convert_art(string memory name, string memory desc, string memory image_url, uint price) public stopFunctioning{ uint id = art_list.length; art_list.push(Art(id,name,desc,image_url,msg.sender,price,msg.sender,false)); _mint(msg.sender,id); emit AddArt(id); } /// @dev Returns the tokens ids for particular owner, uses ERC721 _tokensofOwner /// @param _owner Takes address of owner /// @return count of integers of ids function ownerArtsCount(address _owner) public view returns(uint[] memory){ return _tokensOfOwner(_owner); } /// @notice Transfer the amount equal to price and transfers the ownership of token /// @dev Uses _transferFrom of the ERC721 implementation /// @param id of token function buy_art(uint id) public payable paidEnough(art_list[id].price) onSale(id) stopFunctioning{ address payable _owner = art_list[id].owner; art_list[id].onsale = false; _owner.transfer(msg.value); art_list[id].owner = msg.sender; _transferFrom(_owner, msg.sender, id); } /// @dev Update price of Token /// @param id Token Id /// @param price Price of the collectible function price_update(uint id, uint price) public onlyOwner(id){ art_list[id].price = price; } /// @notice Switch a digital art on/off sale /// @dev Only the owner of token can switch this status /// @param id Id of the token function switchSaleStatus(uint id) public onlyOwner(id){ bool status = art_list[id].onsale; if(status == true){ art_list[id].onsale = false; } else{ art_list[id].onsale = true; } emit SwitchSaleStatus(id, status); } }
@dev Convert a digital art to NFT @param name Name of the Token @param desc Short description of the collectibles @param image_url IPFS url of the image @param price Collectibe sell price @return id of minted token
function convert_art(string memory name, string memory desc, string memory image_url, uint price) public stopFunctioning{ uint id = art_list.length; art_list.push(Art(id,name,desc,image_url,msg.sender,price,msg.sender,false)); _mint(msg.sender,id); emit AddArt(id); }
12,827,499
[ 1, 2723, 279, 25615, 3688, 358, 423, 4464, 225, 508, 1770, 434, 326, 3155, 225, 3044, 7925, 2477, 434, 326, 3274, 495, 1040, 225, 1316, 67, 718, 2971, 4931, 880, 434, 326, 1316, 225, 6205, 9302, 495, 73, 357, 80, 6205, 327, 612, 434, 312, 474, 329, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1765, 67, 485, 12, 1080, 3778, 508, 16, 533, 3778, 3044, 16, 533, 3778, 1316, 67, 718, 16, 2254, 6205, 13, 1071, 2132, 2083, 310, 95, 203, 3639, 2254, 612, 273, 3688, 67, 1098, 18, 2469, 31, 203, 3639, 3688, 67, 1098, 18, 6206, 12, 4411, 12, 350, 16, 529, 16, 5569, 16, 2730, 67, 718, 16, 3576, 18, 15330, 16, 8694, 16, 3576, 18, 15330, 16, 5743, 10019, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 350, 1769, 203, 3639, 3626, 1436, 4411, 12, 350, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3C01af36cCd6bAe6f5CDaf99b7d54D3585AeE475/sources/contracts/extensions/MinterPauserRole.sol
* @dev Adds admin transfer functions to ownership transfer/
function _transferOwnership(address newOwner) internal virtual override { _grantRole(DEFAULT_ADMIN_ROLE, newOwner); _grantRole(MINTER_ROLE, newOwner); _grantRole(PAUSER_ROLE, newOwner); _revokeRole(DEFAULT_ADMIN_ROLE, _msgSender()); _revokeRole(MINTER_ROLE, _msgSender()); _revokeRole(PAUSER_ROLE, _msgSender()); super._transferOwnership(newOwner); }
3,556,151
[ 1, 3655, 3981, 7412, 4186, 358, 23178, 7412, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 5024, 3849, 288, 203, 3639, 389, 16243, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 394, 5541, 1769, 203, 3639, 389, 16243, 2996, 12, 6236, 2560, 67, 16256, 16, 394, 5541, 1769, 203, 3639, 389, 16243, 2996, 12, 4066, 4714, 67, 16256, 16, 394, 5541, 1769, 203, 203, 3639, 389, 9083, 3056, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 9083, 3056, 2996, 12, 6236, 2560, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 9083, 3056, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 2240, 6315, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; import './StandardToken.sol'; import './ERC223ReceivingContract.sol'; /** * @title SimpleToken * @dev ERC20 Token with features insipred by ERC223 allowing transfers to the contract. * Simple version where all tokens are pre-assigned to the creator. * `StandardToken` functions. */ contract JoyToken is StandardToken { string public constant name = "JoyToken"; string public constant symbol = "JOY"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 21000000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ function JoyToken() public { totalSupply = INITIAL_SUPPLY; // update total supply balances[msg.sender] = INITIAL_SUPPLY; // give the creator all initial tokens } // -------------------- features inspired by erc223 idea -------------------- // Event for transfers that contain additional data event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); /** * Function that is called when a user or another contract wants to transfer funds. */ function transfer(address _to, uint _value, bytes _data) 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); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.onTokenReceived(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); return true; } /** * Standard function transfer similar to ERC20 transfer with no _data . * Added due to backwards compatibility reasons. */ function transfer(address _to, uint _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); if (isContract(_to)) { bytes memory _empty_data; ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.onTokenReceived(msg.sender, _value, _empty_data); } Transfer(msg.sender, _to, _value); return true; } /** * @dev Checking if given address is a contract * * Check is made by assemby size of bytecode that can be executed on given eth address, only contracts have it * _addr any eth valid address */ function isContract(address _addr) internal constant returns (bool) { uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_addr) } return (codeLength > 0); } }
give the creator all initial tokens
balances[msg.sender] = INITIAL_SUPPLY;
15,870,795
[ 1, 75, 688, 326, 11784, 777, 2172, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 28226, 67, 13272, 23893, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x6181e2Bcae1f7c1A5B70cF8fa7b62136909B2Efd/sources/contracts/AnyToken.sol
INITIATE ARBITRAGE Begins receiving loan to engage performing arbitrage trades Get the Factory Pair address for combined tokens Return error if combination does not exist Figure out which token (0 or 1) has the amount and assign Passing data as bytes so that the 'swap' function knows it is a flashloan Execute the initial swap to get the loan
function startArbitrage(address _tokenBorrow, uint256 _amount) external { IERC20(tokentobeBorrowed).safeApprove(address(PANCAKE_ROUTER), MAX_INT); IERC20(secondToken).safeApprove(address(PANCAKE_ROUTER), MAX_INT); IERC20(thirdToken).safeApprove(address(PANCAKE_ROUTER), MAX_INT); address pair = IUniswapV2Factory(PANCAKE_FACTORY).getPair( _tokenBorrow, WBNB ); require(pair != address(0), "Pool does not exist"); address token0 = IUniswapV2Pair(pair).token0(); address token1 = IUniswapV2Pair(pair).token1(); uint256 amount0Out = _tokenBorrow == token0 ? _amount : 0; uint256 amount1Out = _tokenBorrow == token1 ? _amount : 0; bytes memory data = abi.encode(_tokenBorrow, _amount, msg.sender); IUniswapV2Pair(pair).swap(amount0Out, amount1Out, address(this), data); }
3,280,675
[ 1, 12919, 45, 1777, 6052, 15650, 54, 2833, 605, 1332, 2679, 15847, 28183, 358, 24691, 410, 14928, 10056, 86, 410, 1284, 5489, 968, 326, 7822, 8599, 1758, 364, 8224, 2430, 2000, 555, 309, 10702, 1552, 486, 1005, 18818, 596, 1492, 1147, 261, 20, 578, 404, 13, 711, 326, 3844, 471, 2683, 31741, 501, 487, 1731, 1427, 716, 326, 296, 22270, 11, 445, 21739, 518, 353, 279, 9563, 383, 304, 7903, 326, 2172, 7720, 358, 336, 326, 28183, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 787, 686, 3682, 86, 410, 12, 2867, 389, 2316, 38, 15318, 16, 2254, 5034, 389, 8949, 13, 3903, 288, 203, 3639, 467, 654, 39, 3462, 12, 17692, 319, 947, 73, 38, 15318, 329, 2934, 4626, 12053, 537, 12, 2867, 12, 30819, 3587, 6859, 67, 1457, 1693, 654, 3631, 4552, 67, 3217, 1769, 203, 3639, 467, 654, 39, 3462, 12, 8538, 1345, 2934, 4626, 12053, 537, 12, 2867, 12, 30819, 3587, 6859, 67, 1457, 1693, 654, 3631, 4552, 67, 3217, 1769, 203, 3639, 467, 654, 39, 3462, 12, 451, 6909, 1345, 2934, 4626, 12053, 537, 12, 2867, 12, 30819, 3587, 6859, 67, 1457, 1693, 654, 3631, 4552, 67, 3217, 1769, 203, 203, 3639, 1758, 3082, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 30819, 3587, 6859, 67, 16193, 2934, 588, 4154, 12, 203, 5411, 389, 2316, 38, 15318, 16, 203, 5411, 678, 15388, 38, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 6017, 480, 1758, 12, 20, 3631, 315, 2864, 1552, 486, 1005, 8863, 203, 203, 3639, 1758, 1147, 20, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 6017, 2934, 2316, 20, 5621, 203, 3639, 1758, 1147, 21, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 6017, 2934, 2316, 21, 5621, 203, 3639, 2254, 5034, 3844, 20, 1182, 273, 389, 2316, 38, 15318, 422, 1147, 20, 692, 389, 8949, 294, 374, 31, 203, 3639, 2254, 5034, 3844, 21, 1182, 273, 389, 2316, 38, 15318, 422, 1147, 21, 692, 389, 8949, 294, 374, 31, 203, 203, 3639, 1731, 2 ]
./full_match/4/0x7d43750B669389fA5349a39bF563B60072C1E8e1/sources/browser/Lottery2.sol
* @dev Set up parameters for new round and start it. Only for owner/
function startNewRound(uint256 newRoundCloseTime, uint256 newBetTimeDelay, uint256 newBetAmount) public onlyOwner { require(!isRoundActive(), "Round must be finished"); require(_prizeFund == 0, "Prize fund must be empty first"); require(newRoundCloseTime > block.timestamp, "Close time must be greater than now"); require(newBetAmount >= 1 * 1e6, "Bet must be greater or equal than 1 * 1e6"); require(newBetTimeDelay >= 60, "Time delay must be greater than 1 minute"); emit NewRoundStarted(block.timestamp, newBetAmount); _roundCloseTime = newRoundCloseTime; _betAmount = newBetAmount; _betTimeDelay = newBetTimeDelay; }
762,452
[ 1, 694, 731, 1472, 364, 394, 3643, 471, 787, 518, 18, 5098, 364, 3410, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 787, 1908, 11066, 12, 11890, 5034, 394, 11066, 4605, 950, 16, 2254, 5034, 394, 38, 278, 950, 6763, 16, 2254, 5034, 394, 38, 278, 6275, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 5, 291, 11066, 3896, 9334, 315, 11066, 1297, 506, 6708, 8863, 203, 3639, 2583, 24899, 683, 554, 42, 1074, 422, 374, 16, 315, 2050, 554, 284, 1074, 1297, 506, 1008, 1122, 8863, 203, 3639, 2583, 12, 2704, 11066, 4605, 950, 405, 1203, 18, 5508, 16, 315, 4605, 813, 1297, 506, 6802, 2353, 2037, 8863, 203, 3639, 2583, 12, 2704, 38, 278, 6275, 1545, 404, 380, 404, 73, 26, 16, 315, 38, 278, 1297, 506, 6802, 578, 3959, 2353, 404, 380, 404, 73, 26, 8863, 203, 3639, 2583, 12, 2704, 38, 278, 950, 6763, 1545, 4752, 16, 315, 950, 4624, 1297, 506, 6802, 2353, 404, 8044, 8863, 203, 203, 3639, 3626, 1166, 11066, 9217, 12, 2629, 18, 5508, 16, 394, 38, 278, 6275, 1769, 203, 203, 3639, 389, 2260, 4605, 950, 273, 394, 11066, 4605, 950, 31, 203, 3639, 389, 70, 278, 6275, 273, 394, 38, 278, 6275, 31, 203, 3639, 389, 70, 278, 950, 6763, 273, 394, 38, 278, 950, 6763, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xb00D4C3A26d8AdC68b9dACe43F3280A2D702f0EC/sources/contracts/Temple.sol
Total allocation points. Must be the sum of all allocation points in all pools.
uint256 private totalAllocPoint = 0;
4,540,324
[ 1, 5269, 13481, 3143, 18, 6753, 506, 326, 2142, 434, 777, 13481, 3143, 316, 777, 16000, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 3238, 2078, 8763, 2148, 273, 374, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xA31f600De4cC2914516976B2de4a82dDC207c861/sources/FGM.sol
Swap Threshold (0.04%)Define 1%Max Tx at Launch
contract FGM is Context, IERC20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balance; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _excludedFromFees; uint256 private constant MAX = ~uint256(0); uint8 private constant _decimals = 18; uint256 private constant _totalSupply = 10**7 * 10**_decimals; uint256 private constant minSwap = 2000 * 10**_decimals; uint256 private constant onePercent = 100000 * 10**_decimals; uint256 public maxTxAmount = onePercent * 2; uint256 private launchBlock; uint256 private db = 0; uint256 private _fee; uint256 public devBuyFee = 0; uint256 public devSellFee = 65; string private constant _name = "Feels Good Man"; string private constant _symbol = "FGM"; IUniswapV2Router02 private uniswapV2Router; address public uniswapV2Pair; address payable public devWallet; bool private tradingEnabled = false; constructor() { uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); devWallet = payable(0x480215990E0632c4d00C1Ce6f618D34CdFe66baB); _balance[msg.sender] = _totalSupply; _excludedFromFees[msg.sender] = true; _excludedFromFees[address(this)] = true; emit Transfer(address(0), _msgSender(), _totalSupply); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balance[account]; } function transfer(address recipient, uint256 amount)public override returns (bool){ _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256){ return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool){ _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub(amount,"ERC20: transfer amount exceeds allowance")); return true; } function _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 Launch() external onlyOwner { tradingEnabled = true; launchBlock = block.number; } function excludeFromFees(address wallet) external onlyOwner { _excludedFromFees[wallet] = true; } function updateTxPercent(uint256 percent) external onlyOwner { maxTxAmount = onePercent * percent; } function removeLimits() external onlyOwner { maxTxAmount = onePercent * 100; } function changeFees(uint256 buy, uint256 sell) external onlyOwner { require(buy < 30); require(sell < 99); devBuyFee = buy; devSellFee = sell; } function _tokenTransfer(address from, address to, uint256 amount) private { uint256 taxTokens = (amount * _fee) / 100; uint256 transferAmount = amount - taxTokens; _balance[from] = _balance[from] - amount; _balance[to] = _balance[to] + transferAmount; _balance[address(this)] = _balance[address(this)] + taxTokens; emit Transfer(from, to, transferAmount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); if (_excludedFromFees[from] || _excludedFromFees[to]) { _fee = 0; require(tradingEnabled, "Trading not open"); require(amount <= maxTxAmount, "MaxTx Enabled at launch"); if (from == uniswapV2Pair) { _fee = devBuyFee; uint256 tokensToSwap = balanceOf(address(this)); if (tokensToSwap > onePercent * 2) { tokensToSwap = onePercent * 2; } swapTokensForEth(tokensToSwap); } _fee = devSellFee; _fee = 0; } } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); if (_excludedFromFees[from] || _excludedFromFees[to]) { _fee = 0; require(tradingEnabled, "Trading not open"); require(amount <= maxTxAmount, "MaxTx Enabled at launch"); if (from == uniswapV2Pair) { _fee = devBuyFee; uint256 tokensToSwap = balanceOf(address(this)); if (tokensToSwap > onePercent * 2) { tokensToSwap = onePercent * 2; } swapTokensForEth(tokensToSwap); } _fee = devSellFee; _fee = 0; } } } else { if (block.number < launchBlock + db) {_fee=99;} else { function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); if (_excludedFromFees[from] || _excludedFromFees[to]) { _fee = 0; require(tradingEnabled, "Trading not open"); require(amount <= maxTxAmount, "MaxTx Enabled at launch"); if (from == uniswapV2Pair) { _fee = devBuyFee; uint256 tokensToSwap = balanceOf(address(this)); if (tokensToSwap > onePercent * 2) { tokensToSwap = onePercent * 2; } swapTokensForEth(tokensToSwap); } _fee = devSellFee; _fee = 0; } } } else if (to == uniswapV2Pair) { function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); if (_excludedFromFees[from] || _excludedFromFees[to]) { _fee = 0; require(tradingEnabled, "Trading not open"); require(amount <= maxTxAmount, "MaxTx Enabled at launch"); if (from == uniswapV2Pair) { _fee = devBuyFee; uint256 tokensToSwap = balanceOf(address(this)); if (tokensToSwap > onePercent * 2) { tokensToSwap = onePercent * 2; } swapTokensForEth(tokensToSwap); } _fee = devSellFee; _fee = 0; } } } else { }
15,615,655
[ 1, 12521, 27139, 261, 20, 18, 3028, 9, 13, 11644, 404, 9, 2747, 6424, 622, 14643, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 29086, 49, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 12296, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 24602, 1265, 2954, 281, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 6549, 31, 203, 565, 2254, 5034, 3238, 5381, 389, 4963, 3088, 1283, 273, 1728, 636, 27, 380, 1728, 636, 67, 31734, 31, 203, 565, 2254, 5034, 3238, 5381, 1131, 12521, 273, 16291, 380, 1728, 636, 67, 31734, 31, 203, 565, 2254, 5034, 3238, 5381, 1245, 8410, 273, 25259, 380, 1728, 636, 67, 31734, 31, 203, 565, 2254, 5034, 1071, 943, 4188, 6275, 273, 1245, 8410, 380, 576, 31, 203, 203, 565, 2254, 5034, 3238, 8037, 1768, 31, 203, 565, 2254, 5034, 3238, 1319, 273, 374, 31, 203, 203, 565, 2254, 5034, 3238, 389, 21386, 31, 203, 565, 2254, 5034, 1071, 4461, 38, 9835, 14667, 273, 374, 31, 203, 565, 2254, 5034, 1071, 4461, 55, 1165, 14667, 273, 15892, 31, 203, 377, 203, 565, 533, 3238, 5381, 389, 529, 273, 315, 2954, 10558, 31732, 8660, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 315, 42, 43, 49, 14432, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 3238, 640, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./Address.sol"; import "./Context.sol"; import "./Strings.sol"; import "./ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IBattleground {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IGOLD { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IRandomizer { function getChunkId() external view returns (uint256); function random(uint256 data) external returns (uint256); function randomChunk(uint256 chunkId, uint256 data) external returns (uint256); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { struct TokenTraits { bool isVillager; uint8 alphaIndex; } function getTokenTraits(uint256 tokenId) external view returns (TokenTraits memory); function generateTokenTraits(uint256 tokenId, uint256 seed) external; } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IVAndV {} // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IVAndVMinter {} // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IVillage { function randomVikingOwner(uint256 seed) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./Address.sol"; import "./Ownable.sol"; import "./Strings.sol"; import "./ERC721Enumerable.sol"; import "./IVAndV.sol"; import "./IVAndVMinter.sol"; import "./ITraits.sol"; import "./IVillage.sol"; import "./IBattleground.sol"; contract VAndV is IVAndV, ERC721Enumerable, Ownable { using Address for address; using Strings for uint256; // max number of tokens that can be minted - 75000 in production uint256 public immutable MAX_TOKENS; // number of tokens that can be claimed for free - 20% of MAX_TOKENS uint256 public immutable PAID_TOKENS; // number of tokens have been minted so far uint16 public minted = 0; // refernece to V&V minter IVAndVMinter private vandvMinter; // reference to village IVillage private village; // reference to battleground (coming soon) IBattleground private battleground; /** * create the contract with a name and symbol and references to other contracts * @param _maxTokens total tokens available */ constructor(uint256 _maxTokens) ERC721("Vikings & Villagers", "VANDV") { MAX_TOKENS = _maxTokens; PAID_TOKENS = _maxTokens / 5; } /** * mint a token to an address * @param to who to send the new token to */ function mint(address to) external returns (uint256) { require(_msgSender() == address(vandvMinter), "V&V: Only minter can call this function"); require(minted + 1 <= MAX_TOKENS, "V&V: All tokens minted"); minted++; _safeMint(to, minted); return minted; } /** * @param tokenId the token ID * @return the token's fully formed URI to get metadata */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked("https://vikingsandvillagers.com/metadata/", tokenId.toString())); } /** * @param from the address sending the token * @param to the address we're sending to * @param tokenId the token ID being transferred */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { // Hardcode approval for our contracts to transfer tokens to prevent users having // to manually approve their token for transfer, saving them gas if (_msgSender() != address(vandvMinter) && _msgSender() != address(village) && _msgSender() != address(battleground)) { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); } _transfer(from, to, tokenId); } /** * get how many tokens have been minted * @return number of tokens minted */ function getMinted() external view returns (uint16) { return minted; } /** * get the number of tokens available for minting ever * @return max tokens */ function getMaxTokens() external view returns (uint256) { return MAX_TOKENS; } /** * get the number of paid tokens * @return total paid tokens */ function getPaidTokens() external view returns (uint256) { return PAID_TOKENS; } /** * set the address of the V&V minter contract * @param _vandvMinter the address */ function setVAndVMinter(address _vandvMinter) external onlyOwner { vandvMinter = IVAndVMinter(_vandvMinter); } /** * set the address of the village contract * @param _village the address */ function setVillage(address _village) external onlyOwner { village = IVillage(_village); } /** * set the address of the battleground contract * doesn't exist yet, will be used in the future * @param _battleground the address */ function setBattleground(address _battleground) external onlyOwner { battleground = IBattleground(_battleground); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./Address.sol"; import "./Ownable.sol"; import "./Pausable.sol"; import "./Strings.sol"; import "./ReentrancyGuard.sol"; import "./IVAndVMinter.sol"; import "./IRandomizer.sol"; import "./ITraits.sol"; import "./IVillage.sol"; import "./IGOLD.sol"; import "./VAndV.sol"; contract VAndVMinterV2 is IVAndVMinter, Ownable, Pausable, ReentrancyGuard { using Address for address; using Strings for uint256; // Events event TokenStolen(address from, address by, uint256 tokenId); // mint price uint256 public constant MINT_PRICE = 0.069 ether; // max mint amount per transaction uint8 public constant MINT_PER_TRANSACTION = 10; // how many paid tokens exist uint256 public constant PAID_TOKENS = 6500; // cap this to 6500 // how many max tokens can be minted uint256 public constant MAX_TOKENS = 32500; // cap this to 32500 // whether the public sale is active bool public saleActive = false; // track which tokens are unrevealed and their chunks mapping(uint256 => uint256) private unrevealedTokens; // reference to randomizer IRandomizer private randomizer; // reference to $GOLD for burning on mint IGOLD private gold; // reference to traits ITraits private traits; // reference to vandv VAndV private vandv; // reference to village IVillage private village; /** * create the contract and auto-pause */ constructor() { _pause(); } /** * check if the sending user can mint * @return if they can mint or not */ function canMint() external view returns (bool) { return !paused() && saleActive && vandv.getMinted() < MAX_TOKENS; } /** * check to see if a token is ready to be revealed * @return if the token can be revealed */ function canReveal(uint256 tokenId) external view returns (bool) { return unrevealedTokens[tokenId] > 0 && randomizer.getChunkId() > unrevealedTokens[tokenId]; } /** * mint tokens * the first 20% cost ETH to claim, the rest cost $GOLD * 10% will become vikings, the rest are villagers * @param amount the number of tokens to mint */ function mint(uint256 amount) external payable nonReentrant whenNotPaused { require(tx.origin == _msgSender() && !_msgSender().isContract(), "V&V: Only EOA"); require(saleActive, "V&V: Sale not active"); require(vandv.getMinted() + amount <= MAX_TOKENS, "V&V: All tokens minted"); require(amount > 0 && amount <= MINT_PER_TRANSACTION, "V&V: Invalid mint amount"); if (vandv.getMinted() < PAID_TOKENS) { require(vandv.getMinted() + amount <= PAID_TOKENS, "V&V: All paid tokens already sold"); require(msg.value == amount * MINT_PRICE, "V&V: Invalid payment amount"); } else { require(msg.value == 0, "V&V: Invalid payment amount"); } _performMint(amount); } /** * reveal a token, assigning it traits and rolling to see if it should get * stolen by a viking * you may have to wait up to an hour to run this function * @param tokenIds the token IDs */ function reveal(uint256[] memory tokenIds) external nonReentrant whenNotPaused { require(tx.origin == _msgSender() && !_msgSender().isContract(), "V&V: Only EOA"); for (uint i = 0; i < tokenIds.length; i++) { require(vandv.ownerOf(tokenIds[i]) == _msgSender(), "V&V: Doesn't own that token"); require(unrevealedTokens[tokenIds[i]] > 0, "V&V: Token has already been revealed"); uint256 chunkId = unrevealedTokens[tokenIds[i]]; uint256 seed = randomizer.randomChunk(chunkId, tokenIds[i]); traits.generateTokenTraits(tokenIds[i], seed); delete unrevealedTokens[tokenIds[i]]; address stolenBy = _rollTokenSteal(tokenIds[i], seed); if (stolenBy != address(0x0)) { vandv.transferFrom(_msgSender(), stolenBy, tokenIds[i]); emit TokenStolen(_msgSender(), stolenBy, tokenIds[i]); } } } /** * set the address of our randomizer contract * @param _randomizer the address */ function setRandomizer(address _randomizer) external onlyOwner { randomizer = IRandomizer(_randomizer); } /** * set the address of the gold contract * @param _gold the address */ function setGold(address _gold) external onlyOwner { gold = IGOLD(_gold); } /** * set the address of the traits contract * @param _traits the address */ function setTraits(address _traits) external onlyOwner { traits = ITraits(_traits); } /** * set the address of our vandv contract * @param _vandv the address */ function setVAndV(address _vandv) external onlyOwner { vandv = VAndV(_vandv); } /** * set the address of the village contract * @param _village the address */ function setVillage(address _village) external onlyOwner { village = IVillage(_village); } /** * add unrevealed tokens from V1 of the minter * @param tokenIds the tokens to add * @param chunkIds the chunks that correspond to the tokens */ function addUnrevealedTokens(uint16[] calldata tokenIds, uint16[] calldata chunkIds) external onlyOwner { for (uint256 i = 0; i < tokenIds.length; i++) { unrevealedTokens[uint256(tokenIds[i])] = uint256(chunkIds[i]); } } /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(_msgSender()).transfer(address(this).balance); } /** * enables owner to pause/unpause minting * @param enabled if we should pause or unpause */ function setPaused(bool enabled) external onlyOwner { if (enabled) { _pause(); } else { _unpause(); } } /** * enables owner to enable and disable the public sale * @param enabled if we should enable or disable public sale */ function setSaleActive(bool enabled) external onlyOwner { saleActive = enabled; } /** * mint tokens, called from either the mint or mintWhitelist functions * @param amount the number of tokens to mint */ function _performMint(uint256 amount) internal { uint256 totalGoldCost = 0; for (uint256 i = 0; i < amount; i++) { totalGoldCost += _mintGoldCost(vandv.getMinted() + i + 1); } if (totalGoldCost > 0) { gold.burn(_msgSender(), totalGoldCost); } for (uint256 i = 0; i < amount; i++) { uint256 tokenId = vandv.mint(_msgSender()); // Track the chunk that the token was minted in +1 so that the reveal of this // chunk's seed can't be sandwiched. This means for the reveal we have to wait // for 2 seed values to get pushed to the randomizer unrevealedTokens[tokenId] = randomizer.getChunkId() + 1; } } /** * the first 20% are paid in ETH, so 0 $GOLD * the next 20% are 20000 $GOLD * the next 20% are 30000 $GOLD * the next 20% are 40000 $GOLD * the final 20% are 60000 $GOLD * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */ function _mintGoldCost(uint256 tokenId) internal pure returns (uint256) { if (tokenId <= PAID_TOKENS) return 0; if (tokenId <= MAX_TOKENS * 2 / 5) return 20000 ether; if (tokenId <= MAX_TOKENS * 3 / 5) return 30000 ether; if (tokenId <= MAX_TOKENS * 4 / 5) return 40000 ether; return 60000 ether; } /** * paid tokens will always go to the minter * tokens bought using $GOLD have a 10% chance to be given to a random staked viking * @param tokenId the token ID * @return the owner of the viking, or blackhole if not stolen */ function _rollTokenSteal(uint256 tokenId, uint256 seed) internal view returns (address) { if (tokenId <= PAID_TOKENS || ((seed >> 245) % 10) != 0) { return address(0x0); } return village.randomVikingOwner(seed); } }
* add unrevealed tokens from V1 of the minter @param tokenIds the tokens to add @param chunkIds the chunks that correspond to the tokens/
function addUnrevealedTokens(uint16[] calldata tokenIds, uint16[] calldata chunkIds) external onlyOwner { for (uint256 i = 0; i < tokenIds.length; i++) { unrevealedTokens[uint256(tokenIds[i])] = uint256(chunkIds[i]); } }
1,356,039
[ 1, 1289, 640, 266, 537, 18931, 2430, 628, 776, 21, 434, 326, 1131, 387, 225, 1147, 2673, 326, 2430, 358, 527, 225, 2441, 2673, 326, 6055, 716, 4325, 358, 326, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 527, 984, 266, 537, 18931, 5157, 12, 11890, 2313, 8526, 745, 892, 1147, 2673, 16, 2254, 2313, 8526, 745, 892, 2441, 2673, 13, 3903, 1338, 5541, 288, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1147, 2673, 18, 2469, 31, 277, 27245, 288, 203, 1377, 640, 266, 537, 18931, 5157, 63, 11890, 5034, 12, 2316, 2673, 63, 77, 5717, 65, 273, 2254, 5034, 12, 6551, 2673, 63, 77, 19226, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account&#39;s access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract MasterRole { using Roles for Roles.Role; event MasterAdded(address indexed account); event MasterRemoved(address indexed account); Roles.Role private masters; constructor() internal { _addMaster(msg.sender); } modifier onlyMaster() { require(isMaster(msg.sender)); _; } function isMaster(address account) public view returns (bool) { return masters.has(account); } function addMaster(address account) public onlyMaster { _addMaster(account); } function renounceMaster() public { _removeMaster(msg.sender); } function _addMaster(address account) internal { masters.add(account); emit MasterAdded(account); } function _removeMaster(address account) internal { masters.remove(account); emit MasterRemoved(account); } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private minters; constructor() internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { minters.remove(account); emit MinterRemoved(account); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); event TransferWithData( address indexed from, address indexed to, bytes32 indexed data, uint256 value ); } 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; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract AddressMapper is MasterRole { event DoMap(address indexed src, bytes32 indexed target, string rawTarget); event DoMapAuto(address indexed src, bytes32 indexed target, string rawTarget); event UnMap(address indexed src); mapping (address => string) public mapper; modifier onlyNotSet(address src) { bytes memory tmpTargetBytes = bytes(mapper[src]); require(tmpTargetBytes.length == 0); _; } function() public payable onlyNotSet(msg.sender) { require(msg.value > 0); _doMapAuto(msg.sender, string(msg.data)); msg.sender.transfer(msg.value); } function isAddressSet(address thisAddr) public view returns(bool) { bytes memory tmpTargetBytes = bytes(mapper[thisAddr]); if(tmpTargetBytes.length == 0) { return false; } else { return true; } } function _doMapAuto(address src, string target) internal { mapper[src] = target; bytes32 translated = _stringToBytes32(target); emit DoMapAuto(src, translated, target); } function doMap(address src, string target) public onlyMaster onlyNotSet(src) { mapper[src] = target; bytes32 translated = _stringToBytes32(target); emit DoMap(src, translated, target); } function unMap(address src) public onlyMaster { mapper[src] = ""; emit UnMap(src); } function _stringToBytes32(string memory source) internal returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function submitTransaction(address destination, uint value, bytes data) public onlyMaster { external_call(destination, value, data.length, data); } function external_call(address destination, uint value, uint dataLength, bytes data) private returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; AddressMapper public addressMapper; constructor(address addressMapperAddr) public { addressMapper = AddressMapper(addressMapperAddr); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, to, value); return true; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. * @param data addtional data. */ function transferWithData(address to, uint256 value, bytes32 data) public returns (bool) { _transfer(msg.sender, to, value); emit TransferWithData(msg.sender, to, data, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred * @param data addtional data. */ function transferFromWithData( address from, address to, uint256 value, bytes32 data ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit TransferWithData(from, to, data, value); return true; } /** * @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 increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender&#39;s allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { constructor(address addressMapperAddr) ERC20(addressMapperAddr) public {} /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address to, uint256 value ) public onlyMinter returns (bool) { _mint(to, value); return true; } } /** * @title Capped token * @dev Mintable token with a token cap. */ contract ERC20Capped is ERC20Mintable { event SetIsPreventedAddr(address indexed preventedAddr, bool hbool); uint256 private _cap; string private _name; string private _symbol; uint8 private _decimals; mapping ( address => bool ) public isPreventedAddr; function transfer(address to, uint256 value) public returns (bool) { _checkedTransfer(msg.sender, to, value); return true; } function transferWithData(address to, uint256 value, bytes32 data) public returns (bool) { _checkedTransfer(msg.sender, to, value); emit TransferWithData(msg.sender, to, data, value); return true; } function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _checkedTransfer(from, to, value); return true; } function transferFromWithData( address from, address to, uint256 value, bytes32 data ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _checkedTransfer(from, to, value); emit TransferWithData(from, to, data, value); return true; } function _checkedTransfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); if(isPreventedAddr[to]) { require(addressMapper.isAddressSet(from)); } _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function setIsPreventedAddr(address thisAddr, bool hbool) public onlyMinter { isPreventedAddr[thisAddr] = hbool; emit SetIsPreventedAddr(thisAddr, hbool); } constructor(address addressMapperAddr, uint256 cap, string name, string symbol, uint8 decimals) ERC20Mintable(addressMapperAddr) public { require(cap > 0); _cap = cap; _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the cap for the token minting. */ function cap() public view returns(uint256) { return _cap; } function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap); super._mint(account, value); } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } }
* @dev Transfer token for a specified address @param to The address to transfer to. @param value The amount to be transferred. @param data addtional data./
function transferWithData(address to, uint256 value, bytes32 data) public returns (bool) { _transfer(msg.sender, to, value); emit TransferWithData(msg.sender, to, data, value); return true; }
10,679,255
[ 1, 5912, 1147, 364, 279, 1269, 1758, 225, 358, 1021, 1758, 358, 7412, 358, 18, 225, 460, 1021, 3844, 358, 506, 906, 4193, 18, 225, 501, 527, 24252, 287, 501, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1190, 751, 12, 2867, 358, 16, 2254, 5034, 460, 16, 1731, 1578, 501, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 389, 13866, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 565, 3626, 12279, 1190, 751, 12, 3576, 18, 15330, 16, 358, 16, 501, 16, 460, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x86F25b64e1Fe4C5162cDEeD5245575D32eC549db/sources/BalanceScanner.sol
* @notice Get the ERC-20 token balance of `token` for all addresses specified @dev This does not check if the `token` address specified is actually an ERC-20 token @param addresses The addresses to get the token balance for @param token The address of the ERC-20 token contract @return balances The token balance for all addresses in the same order as specified/
function tokenBalances(address[] calldata addresses, address token) external returns (uint256[] memory balances) { balances = new uint256[](addresses.length); for (uint256 i = 0; i < addresses.length; i++) { balances[i] = tokenBalance(addresses[i], token); } }
9,307,420
[ 1, 967, 326, 4232, 39, 17, 3462, 1147, 11013, 434, 1375, 2316, 68, 364, 777, 6138, 1269, 225, 1220, 1552, 486, 866, 309, 326, 1375, 2316, 68, 1758, 1269, 353, 6013, 392, 4232, 39, 17, 3462, 1147, 225, 6138, 1021, 6138, 358, 336, 326, 1147, 11013, 364, 225, 1147, 1021, 1758, 434, 326, 4232, 39, 17, 3462, 1147, 6835, 327, 324, 26488, 1021, 1147, 11013, 364, 777, 6138, 316, 326, 1967, 1353, 487, 1269, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1147, 38, 26488, 12, 2867, 8526, 745, 892, 6138, 16, 1758, 1147, 13, 3903, 1135, 261, 11890, 5034, 8526, 3778, 324, 26488, 13, 288, 203, 565, 324, 26488, 273, 394, 2254, 5034, 8526, 12, 13277, 18, 2469, 1769, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 6138, 18, 2469, 31, 277, 27245, 288, 203, 1377, 324, 26488, 63, 77, 65, 273, 1147, 13937, 12, 13277, 63, 77, 6487, 1147, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x2d92d57FBef4e333e0FB8629266fC761b5f156cd/sources/browser/JasmyDepositSwapper.sol
Prices:--------------------------------------------------------------------------------------------------------------------------------------
function setPrices(uint256 _ethPrice, uint256 _usdtPrice) external { require(msg.sender == owner, ERR_MSG_SENDER); if(_ethPrice > 0) { ethPrice = _ethPrice; } if(_usdtPrice > 0) { usdtPrice = _usdtPrice; } }
8,301,074
[ 1, 31862, 30, 5802, 5802, 13093, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 31862, 12, 11890, 5034, 389, 546, 5147, 16, 2254, 5034, 389, 407, 7510, 5147, 13, 3903, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 10359, 67, 11210, 67, 1090, 18556, 1769, 203, 540, 203, 3639, 309, 24899, 546, 5147, 405, 374, 13, 203, 3639, 288, 203, 5411, 13750, 5147, 273, 389, 546, 5147, 31, 203, 3639, 289, 203, 540, 203, 3639, 309, 24899, 407, 7510, 5147, 405, 374, 13, 203, 3639, 288, 203, 5411, 584, 7510, 5147, 273, 389, 407, 7510, 5147, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* The Sale contract manages a token sale. The Sale contract primarily does the following: - allows individuals to buy tokens during a token sale - allows individuals to claim the tokens after a successful token sale - allows individuals to receive an ETH refund after a cancelled token sale - allows an admin to cancel a token sale, after which individuals can request refunds - allows an admin to certify a token sale, after which an admin can withdraw contributed ETH - allows an admin to complete a token sale, after which an individual (following a brief release period) can request their tokens - allows an admin to return contributed ETH to individuals - allows an admin to grant tokens to an individual - allows an admin to withdraw ETH from the token sale - allows an admin to add and remove individuals from a whitelist - allows an admin to pause or activate the token sale The sale runs from a start timestamp to a finish timestamp. After the release timestamp (assuming a successful sale), individuals can claim their tokens. If the sale is cancelled, individuals can request a refund. Furthermore, an admin may return ETH and negate purchases to respective individuals as deemed necessary. Once the sale is certified or completed, ETH can be withdrawn by the company. The contract creator appoints a delegate to perform most administrative tasks. All events are logged for the purpose of transparency. All math uses SafeMath. ETH and tokens (often referred to as "value" and "tokens" in variable names) are really 1/10^18 of their respective parent units. Basically, the values represent wei and the token equivalent thereof. */ pragma solidity ^0.4.18; contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } contract SaleCallbackInterface { function handleSaleCompletionCallback(uint256 _tokens) external payable returns (bool); function handleSaleClaimCallback(address _recipient, uint256 _tokens) external returns (bool); } contract Sale is SafeMath { address public creator; // address of the contract's creator address public delegate; // address of an entity allowed to perform administrative functions on behalf of the creator address public marketplace; // address of another smart contract that manages the token and Smart Exchange uint256 public start; // timestamp that the sale begins uint256 public finish; // timestamp that the sale ends uint256 public release; // timestamp that sale participants may "claim" their tokens (will be after the finish) uint256 public pricer; // a multiplier (>= 1) used to determine how many tokens (or, really, 10^18 sub-units of that token) to give purchasers uint256 public size; // maximum number of 10^18 sub-units of tokens that can be purchased/granted during the sale bool public restricted; // whether purchasers and recipients of tokens must be whitelisted manually prior to participating in the sale bool public active; // whether individuals are allowed to purchase tokens -- if false, they cannot. if true, they can or cannot. // other factors, like start/finish, size, and others can restrict participation as well, even if active = true. // this also can remain true indefinitely, even if the token sale has been cancelled or has completed. int8 public progress; // -1 = token sale cancelled, 0 = token sale ongoing, 1 = token sale certified (can withdraw ETH while sale is live), 2 = token sale completed uint256 public tokens; // number of sub-tokens that have been purchased/granted during the sale. purchases/grants can be reversed while progress = 0 || progress = 1 resulting in tokens going down uint256 public value; // number of sub-ether (wei) that have been contributed during the sale. purchases can be resversed while progress = 0 || progress = 1 resulting in value going down uint256 public withdrawls; // the number of sub-ether (wei) that have been withdrawn by the contract owner uint256 public reserves; // the number of sub-ether (wei) that have been sent to serve as reserve in the marketplace mapping(address => bool) public participants; // mapping to record who has participated in the sale (purchased/granted) address[] public participantIndex; // index of participants mapping(address => uint256) public participantTokens; // sub-tokens purchased/granted to each participant mapping(address => uint256) public participantValues; // sub-ether contributed by each participant mapping(address => bool) public participantRefunds; // mapping to record who has been awarded a refund after a cancelled sale mapping(address => bool) public participantClaims; // mapping to record who has claimed their tokens after a completed sale mapping(address => bool) public whitelist; // mapping to record who has been approved to participate in a "restricted" sale uint256[] public bonuses; // stores bonus percentages, where even numbered elements store timestamps and odd numbered elements store bonus percentages bool public mutable; // whether certain properties (like finish and release) of the sale can be updated to increase the liklihood of a successful token sale for all parties involved modifier ifCreator { require(msg.sender == creator); _; } // if the caller created the contract... modifier ifDelegate { require(msg.sender == delegate); _; } // if the caller is currently the appointed delegate... modifier ifMutable { require(mutable); _; } // if the certain properties of the sale can be changed.... event Created(); // the contract was created event Bought(address indexed _buyer, address indexed _recipient, uint256 _tokens, uint256 _value); // an individual bought tokens event Claimed(address indexed _recipient, uint256 _tokens); // an individual claimed tokens after the completion of the sale and after tokens were scheduled for release event Refunded(address indexed _recipient, uint256 _value); // an individual requested a refund of the ETH they contributed after a cancelled token sale event Reversed(address indexed _recipient, uint256 _tokens, uint256 _value); // an individual was sent the ETH they contributed to the sale and will not receive tokens event Granted(address indexed _recipient, uint256 _tokens); // an individual was granted tokens, without contributing ETH event Withdrew(address _recipient, uint256 _value); // the contract creator withdrew ETH from the token sale event Completed(uint256 _tokens, uint256 _value, uint256 _reserves); // the contract creator signaled that the sale completed successfuly event Certified(uint256 _tokens, uint256 _value); // the contract creator certified the sale event Cancelled(uint256 _tokens, uint256 _value); // the contract creator cancelled the sale event Listed(address _participant); // an individual was added to the whitelist event Delisted(address _participant); // an individual was removed from the whitelist event Paused(); // the sale was paused (active = false) event Activated(); // the sale was activated (active = true) function Sale() { creator = msg.sender; delegate = msg.sender; start = 1; // contributions may be made as soon as the contract is published finish = 1535760000; // the sale continues through 09/01/2018 @ 00:00:00 release = 1536969600; // tokens will be available to participants starting 09/15/2018 @ 00:00:00 pricer = 100000; // each ETH is worth 100,000 tokens size = 10 ** 18 * pricer * 2000 * 2; // 2,000 ETH, plus a 100% buffer to account for the possibility of a 50% decrease in ETH value during the sale restricted = false; // the sale accepts contributions from everyone. // however, participants who do not submit formal KYC verification before the end of the token sale will have their contributions reverted bonuses = [1, 20]; // the bonus during the pre-sale starts at 20% mutable = true; // certain attributes, such as token sale finish and release dates, may be updated to increase the liklihood of a successful token sale for all parties involved active = true; // the token sale is active from the point the contract is published in the form of a pre-sale Created(); Activated(); } // returns the number of sub-tokens the calling account purchased/was granted function getMyTokenBalance() external constant returns (uint256) { return participantTokens[msg.sender]; } // allows an individual to buy tokens (which will not be issued immediately) // individual instructs the tokens to be delivered to a specific account, which may be different than msg.sender function buy(address _recipient) public payable { // _recipient address must not be all 0's require(_recipient != address(0x0)); // contributor must send more than 1/10 ETH require(msg.value >= 10 ** 17); // sale must be considered active require(active); // sale must be ongoing or certified require(progress == 0 || progress == 1); // current timestamp must be greater than or equal to the start of the token sale require(block.timestamp >= start); // current timestamp must be less than the end of the token sale require(block.timestamp < finish); // either the token sale isn't restricted, or the sender is on the whitelist require((! restricted) || whitelist[msg.sender]); // either the token sale isn't restricted, or the recipient is on the whitelist require((! restricted) || whitelist[_recipient]); // multiply sub-ether by the pricer (which will be a whole number >= 1) to get sub-tokens uint256 baseTokens = safeMul(msg.value, pricer); // determine how many bonus sub-tokens to award and add that to the base tokens uint256 totalTokens = safeAdd(baseTokens, safeDiv(safeMul(baseTokens, getBonusPercentage()), 100)); // ensure the purchase does not cause the sale to exceed its maximum size require(safeAdd(tokens, totalTokens) <= size); // if the recipient is new, add them as a participant if (! participants[_recipient]) { participants[_recipient] = true; participantIndex.push(_recipient); } // increment the participant's sub-tokens and sub-ether participantTokens[_recipient] = safeAdd(participantTokens[_recipient], totalTokens); participantValues[_recipient] = safeAdd(participantValues[_recipient], msg.value); // increment sale sub-tokens and sub-ether tokens = safeAdd(tokens, totalTokens); value = safeAdd(value, msg.value); // log purchase event Bought(msg.sender, _recipient, totalTokens, msg.value); } // token sale participants call this to claim their tokens after the sale is completed and tokens are scheduled for release function claim() external { // sale must be completed require(progress == 2); // tokens must be scheduled for release require(block.timestamp >= release); // participant must have tokens to claim require(participantTokens[msg.sender] > 0); // participant must not have already claimed tokens require(! participantClaims[msg.sender]); // record that the participant claimed their tokens participantClaims[msg.sender] = true; // log the event Claimed(msg.sender, participantTokens[msg.sender]); // call the marketplace contract, which will actually issue the tokens to the participant SaleCallbackInterface(marketplace).handleSaleClaimCallback(msg.sender, participantTokens[msg.sender]); } // token sale participants call this to request a refund if the sale was cancelled function refund() external { // the sale must be cancelled require(progress == -1); // the participant must have contributed ETH require(participantValues[msg.sender] > 0); // the participant must not have already requested a refund require(! participantRefunds[msg.sender]); // record that the participant requested a refund participantRefunds[msg.sender] = true; // log the event Refunded(msg.sender, participantValues[msg.sender]); // transfer contributed ETH back to the participant address(msg.sender).transfer(participantValues[msg.sender]); } // the contract creator calls this to withdraw contributed ETH to a specific address function withdraw(uint256 _sanity, address _recipient, uint256 _value) ifCreator external { // avoid unintended transaction calls require(_sanity == 100010001); // address must not be 0-value require(_recipient != address(0x0)); // token sale must be certified or completed require(progress == 1 || progress == 2); // the amount of ETH in the contract must be greater than the amount the creator is attempting to withdraw require(this.balance >= _value); // increment the amount that's been withdrawn withdrawls = safeAdd(withdrawls, _value); // log the withdrawl Withdrew(_recipient, _value); // send the ETH to the recipient address(_recipient).transfer(_value); } // the contract owner calls this to complete (finalize/wrap up, etc.) the sale function complete(uint256 _sanity, uint256 _value) ifCreator external { // avoid unintended transaction calls require(_sanity == 101010101); // the sale must be marked as ongoing or certified (aka, not cancelled -1) require(progress == 0 || progress == 1); // the sale can only be completed after the finish time require(block.timestamp >= finish); // ETH is withdrawn in the process and sent to the marketplace contract. ensure the amount that is being withdrawn is greater than the balance in the smart contract. require(this.balance >= _value); // mark the sale as completed progress = 2; // the amount that is sent to the other contract is added to the ETH reserve. denote this amount as reserves. reserves = safeAdd(reserves, _value); // log the completion of the sale, including the number of sub-tokens created by the sale, the amount of net sub-eth received during the sale, and the amount of sub-eth to be added to the reserve Completed(tokens, value, _value); // call the marketplace contract, sending the ETH for the reserve and including the number of sub-tokens SaleCallbackInterface(marketplace).handleSaleCompletionCallback.value(_value)(tokens); } // the creator can certify a sale, meaning it cannot be cancelled, and ETH can be withdrawn from the sale by the creator function certify(uint256 _sanity) ifCreator external { // avoid unintended transaction calls require(_sanity == 101011111); // the sale must be ongoing require(progress == 0); // the sale must have started require(block.timestamp >= start); // record that the sale is certified progress = 1; // log the certification Certified(tokens, value); } // the creator can cancel a sale function cancel(uint256 _sanity) ifCreator external { // avoid unintended transaction calls require(_sanity == 111110101); // the sale must be ongoing require(progress == 0); // record that the sale is cancelled progress = -1; // log the cancellation Cancelled(tokens, value); } // called by the delegate to reverse purchases/grants for a particular contributor function reverse(address _recipient) ifDelegate external { // the recipient address must not be all 0's require(_recipient != address(0x0)); // the sale must be ongoing or certified require(progress == 0 || progress == 1); // the recipient must have contributed ETH and/or received tokens require(participantTokens[_recipient] > 0 || participantValues[_recipient] > 0); uint256 initialParticipantTokens = participantTokens[_recipient]; uint256 initialParticipantValue = participantValues[_recipient]; // subtract sub-tokens and sub-ether from sale totals tokens = safeSub(tokens, initialParticipantTokens); value = safeSub(value, initialParticipantValue); // reset participant sub-tokens and sub-ether participantTokens[_recipient] = 0; participantValues[_recipient] = 0; // log the reversal, including the initial sub-tokens and initial sub-ether Reversed(_recipient, initialParticipantTokens, initialParticipantValue); // if the participant previously sent ETH, return it if (initialParticipantValue > 0) { address(_recipient).transfer(initialParticipantValue); } } // called by the delegate to grant tokens to a recipient function grant(address _recipient, uint256 _tokens) ifDelegate external { // the recipient's address cannot be 0-value require(_recipient != address(0x0)); // the sale must be ongoing or certified require(progress == 0 || progress == 1); // if the recipient has not participated previously, add them as a participant if (! participants[_recipient]) { participants[_recipient] = true; participantIndex.push(_recipient); } // add sub-tokens to the recipient's balance participantTokens[_recipient] = safeAdd(participantTokens[_recipient], _tokens); // add sub-tokens to the sale's total tokens = safeAdd(tokens, _tokens); // log the grant Granted(_recipient, _tokens); } // adds a set of addresses to the whitelist function list(address[] _addresses) ifDelegate external { for (uint256 i = 0; i < _addresses.length; i++) { whitelist[_addresses[i]] = true; Listed(_addresses[i]); } } // removes a set of addresses from the whitelist function delist(address[] _addresses) ifDelegate external { for (uint256 i = 0; i < _addresses.length; i++) { whitelist[_addresses[i]] = false; Delisted(_addresses[i]); } } // pause the sale function pause() ifDelegate external { active = false; Paused(); } // activate the sale function activate() ifDelegate external { active = true; Activated(); } function setDelegate(address _delegate) ifCreator external { delegate = _delegate; } function setRestricted(bool _restricted) ifDelegate external { restricted = _restricted; } function setMarketplace(address _marketplace) ifCreator ifMutable external { marketplace = _marketplace; } function setBonuses(uint256[] _bonuses) ifDelegate ifMutable external { bonuses = _bonuses; } function setFinish(uint256 _finish) ifDelegate ifMutable external { finish = _finish; } function setRelease(uint256 _release) ifDelegate ifMutable external { release = _release; } // get the current bonus percentage, as a whole number function getBonusPercentage() public constant returns (uint256) { uint256 finalBonus; uint256 iterativeTimestamp; uint256 iterativeBonus; // within bonuses, even numbered elements store timestamps and odd numbered elements store bonus percentages // timestamps are in order from oldest to newest // iterates over the elements and if the timestamp has been surpassed, the bonus percentage is denoted // the last bonus percentage that was denoted, if one was denoted at all, is the correct bonus percentage at this time for (uint256 i = 0; i < bonuses.length; i++) { if (i % 2 == 0) { iterativeTimestamp = bonuses[i]; } else { iterativeBonus = bonuses[i]; if (block.timestamp >= iterativeTimestamp) { finalBonus = iterativeBonus; } } } return finalBonus; } function() public payable { buy(msg.sender); } }
timestamp that the sale ends
uint256 public finish;
7,243,713
[ 1, 5508, 716, 326, 272, 5349, 3930, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 4076, 31, 9506, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; contract MetaColonialists is ERC721Enumerable, Ownable { // Accounts address private constant creator0Address = 0xEf27AA93c2906472E880e99f65B408dFEE1124F3; address private constant creator1Address = 0xbAD9802234df34D56f2081B5e00572dEc75156e5; address private constant creator2Address = 0x43cc5BEA362cAffa79d56873Ba9EDb6c01dB5281; // Minting Variables uint256 public maxSupply = 8872; uint256 public mintPrice = 0.15 ether; uint256 public maxPurchase = 2; // Sale Status bool public presaleActive; bool public raffaleSaleActive; bool public publicSaleActive; bool public locked; // Merkle Roots bytes32 private modRoot; bytes32 private ogWhitelistRoot; bytes32 private whitelistRoot; bytes32 private raffleRoot; mapping(address => uint256) private mintCounts; // Metadata string _baseTokenURI; // Events event PublicSaleActivation(bool isActive); event PresaleActivation(bool isActive); event RaffleSaleActivation(bool isActive); constructor() ERC721("Meta Colonialists", "MC") {} // Merkle Proofs function setModRoot(bytes32 _root) external onlyOwner { modRoot = _root; } function setOGWhitelistRoot(bytes32 _root) external onlyOwner { ogWhitelistRoot = _root; } function setWhitelistRoot(bytes32 _root) external onlyOwner { whitelistRoot = _root; } function setRaffleRoot(bytes32 _root) external onlyOwner { raffleRoot = _root; } function _leaf(address _account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_account)); } function isInTree( address _account, bytes32[] calldata _proof, bytes32 _root ) internal pure returns (bool) { return MerkleProof.verify(_proof, _root, _leaf(_account)); } // Minting function ownerMint(address _to, uint256 _count) external onlyOwner { require(totalSupply() + _count <= 8888, "Exceeds max supply"); for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(_to, mintIndex); } } function modMint(uint256 _count, bytes32[] calldata _proof) external { require(presaleActive, "Presale must be active"); require(isInTree(msg.sender, _proof, modRoot), "Not on mod wl"); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function ogPresaleMint(uint256 _count, bytes32[] calldata _proof) external payable { require(presaleActive, "Presale must be active"); require( isInTree(msg.sender, _proof, ogWhitelistRoot), "Not on presale wl" ); require( balanceOf(msg.sender) + _count <= 3, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( 0.14 ether * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= 3, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function presaleMint(uint256 _count, bytes32[] calldata _proof) external payable { require(presaleActive, "Presale must be active"); require( isInTree(msg.sender, _proof, whitelistRoot), "Not on presale wl" ); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintPrice * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function raffleMint(uint256 _count, bytes32[] calldata _proof) external payable { require(raffaleSaleActive, "RaffaleSale must be active"); require( isInTree(msg.sender, _proof, raffleRoot), "Not on raffle wl" ); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's presale quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintPrice * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function mint(uint256 _count) external payable { require(publicSaleActive, "Sale must be active"); require(_count <= maxPurchase, "Exceeds maximum purchase amount"); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintPrice * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } // Configurations function lockMetadata() external onlyOwner { locked = true; } function togglePresaleStatus() external onlyOwner { presaleActive = !presaleActive; emit PresaleActivation(presaleActive); } function toggleRafflesaleStatus() external onlyOwner { raffaleSaleActive = !raffaleSaleActive; emit RaffleSaleActivation(raffaleSaleActive); } function toggleSaleStatus() external onlyOwner { publicSaleActive = !publicSaleActive; emit PublicSaleActivation(publicSaleActive); } function setMintPrice(uint256 _mintPrice) external onlyOwner { mintPrice = _mintPrice; } function setMaxPurchase(uint256 _maxPurchase) external onlyOwner { maxPurchase = _maxPurchase; } function withdrawAll() public onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "Balance can't be zero"); uint256 creator1Dividend = (balance / 100) * 25; uint256 creator2Dividend = ((balance / 100) * 5) + (balance / 400); payable(creator1Address).transfer(creator1Dividend); payable(creator2Address).transfer(creator2Dividend); payable(creator0Address).transfer(address(this).balance); } function getTotalSupply() external view returns (uint256) { return totalSupply(); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function setBaseURI(string memory baseURI) external onlyOwner { require(!locked, "Contract metadata methods are locked"); _baseTokenURI = baseURI; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Accounts Minting Variables Sale Status Merkle Roots Metadata Events Merkle Proofs
contract MetaColonialists is ERC721Enumerable, Ownable { address private constant creator0Address = 0xEf27AA93c2906472E880e99f65B408dFEE1124F3; address private constant creator1Address = 0xbAD9802234df34D56f2081B5e00572dEc75156e5; address private constant creator2Address = 0x43cc5BEA362cAffa79d56873Ba9EDb6c01dB5281; uint256 public maxSupply = 8872; uint256 public mintPrice = 0.15 ether; uint256 public maxPurchase = 2; bool public presaleActive; bool public raffaleSaleActive; bool public publicSaleActive; bool public locked; bytes32 private modRoot; bytes32 private ogWhitelistRoot; bytes32 private whitelistRoot; bytes32 private raffleRoot; mapping(address => uint256) private mintCounts; string _baseTokenURI; event PublicSaleActivation(bool isActive); event PresaleActivation(bool isActive); event RaffleSaleActivation(bool isActive); constructor() ERC721("Meta Colonialists", "MC") {} function setModRoot(bytes32 _root) external onlyOwner { modRoot = _root; } function setOGWhitelistRoot(bytes32 _root) external onlyOwner { ogWhitelistRoot = _root; } function setWhitelistRoot(bytes32 _root) external onlyOwner { whitelistRoot = _root; } function setRaffleRoot(bytes32 _root) external onlyOwner { raffleRoot = _root; } function _leaf(address _account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_account)); } function isInTree( address _account, bytes32[] calldata _proof, bytes32 _root ) internal pure returns (bool) { return MerkleProof.verify(_proof, _root, _leaf(_account)); } function ownerMint(address _to, uint256 _count) external onlyOwner { require(totalSupply() + _count <= 8888, "Exceeds max supply"); for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(_to, mintIndex); } } function ownerMint(address _to, uint256 _count) external onlyOwner { require(totalSupply() + _count <= 8888, "Exceeds max supply"); for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(_to, mintIndex); } } function modMint(uint256 _count, bytes32[] calldata _proof) external { require(presaleActive, "Presale must be active"); require(isInTree(msg.sender, _proof, modRoot), "Not on mod wl"); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function modMint(uint256 _count, bytes32[] calldata _proof) external { require(presaleActive, "Presale must be active"); require(isInTree(msg.sender, _proof, modRoot), "Not on mod wl"); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function ogPresaleMint(uint256 _count, bytes32[] calldata _proof) external payable { require(presaleActive, "Presale must be active"); require( isInTree(msg.sender, _proof, ogWhitelistRoot), "Not on presale wl" ); require( balanceOf(msg.sender) + _count <= 3, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( 0.14 ether * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= 3, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function ogPresaleMint(uint256 _count, bytes32[] calldata _proof) external payable { require(presaleActive, "Presale must be active"); require( isInTree(msg.sender, _proof, ogWhitelistRoot), "Not on presale wl" ); require( balanceOf(msg.sender) + _count <= 3, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( 0.14 ether * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= 3, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function presaleMint(uint256 _count, bytes32[] calldata _proof) external payable { require(presaleActive, "Presale must be active"); require( isInTree(msg.sender, _proof, whitelistRoot), "Not on presale wl" ); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintPrice * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function presaleMint(uint256 _count, bytes32[] calldata _proof) external payable { require(presaleActive, "Presale must be active"); require( isInTree(msg.sender, _proof, whitelistRoot), "Not on presale wl" ); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintPrice * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function raffleMint(uint256 _count, bytes32[] calldata _proof) external payable { require(raffaleSaleActive, "RaffaleSale must be active"); require( isInTree(msg.sender, _proof, raffleRoot), "Not on raffle wl" ); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's presale quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintPrice * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function raffleMint(uint256 _count, bytes32[] calldata _proof) external payable { require(raffaleSaleActive, "RaffaleSale must be active"); require( isInTree(msg.sender, _proof, raffleRoot), "Not on raffle wl" ); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's presale quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintPrice * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function mint(uint256 _count) external payable { require(publicSaleActive, "Sale must be active"); require(_count <= maxPurchase, "Exceeds maximum purchase amount"); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintPrice * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function mint(uint256 _count) external payable { require(publicSaleActive, "Sale must be active"); require(_count <= maxPurchase, "Exceeds maximum purchase amount"); require( balanceOf(msg.sender) + _count <= maxPurchase, "Exceeds the account's quota" ); require(totalSupply() + _count <= maxSupply, "Exceeds max supply"); require( mintPrice * _count <= msg.value, "Ether value sent is not correct" ); require( mintCounts[msg.sender] + _count <= maxPurchase, "Exceeds the account's quota" ); mintCounts[msg.sender] = mintCounts[msg.sender] + _count; for (uint256 i = 0; i < _count; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function lockMetadata() external onlyOwner { locked = true; } function togglePresaleStatus() external onlyOwner { presaleActive = !presaleActive; emit PresaleActivation(presaleActive); } function toggleRafflesaleStatus() external onlyOwner { raffaleSaleActive = !raffaleSaleActive; emit RaffleSaleActivation(raffaleSaleActive); } function toggleSaleStatus() external onlyOwner { publicSaleActive = !publicSaleActive; emit PublicSaleActivation(publicSaleActive); } function setMintPrice(uint256 _mintPrice) external onlyOwner { mintPrice = _mintPrice; } function setMaxPurchase(uint256 _maxPurchase) external onlyOwner { maxPurchase = _maxPurchase; } function withdrawAll() public onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "Balance can't be zero"); uint256 creator1Dividend = (balance / 100) * 25; uint256 creator2Dividend = ((balance / 100) * 5) + (balance / 400); payable(creator1Address).transfer(creator1Dividend); payable(creator2Address).transfer(creator2Dividend); payable(creator0Address).transfer(address(this).balance); } function getTotalSupply() external view returns (uint256) { return totalSupply(); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function setBaseURI(string memory baseURI) external onlyOwner { require(!locked, "Contract metadata methods are locked"); _baseTokenURI = baseURI; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } }
225,255
[ 1, 13971, 490, 474, 310, 23536, 348, 5349, 2685, 31827, 7450, 87, 6912, 9043, 31827, 1186, 792, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6565, 19636, 649, 1486, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 288, 203, 565, 1758, 3238, 5381, 11784, 20, 1887, 273, 203, 3639, 374, 17432, 74, 5324, 5284, 11180, 71, 5540, 20, 1105, 9060, 41, 28, 3672, 73, 2733, 74, 9222, 38, 24, 6840, 72, 8090, 41, 17666, 24, 42, 23, 31, 203, 565, 1758, 3238, 5381, 11784, 21, 1887, 273, 203, 3639, 374, 6114, 1880, 10689, 3103, 17959, 2180, 5026, 40, 4313, 74, 3462, 11861, 38, 25, 73, 28564, 9060, 72, 23057, 5877, 28946, 73, 25, 31, 203, 565, 1758, 3238, 5381, 11784, 22, 1887, 273, 203, 3639, 374, 92, 8942, 952, 25, 5948, 37, 5718, 22, 71, 12664, 507, 7235, 72, 4313, 28, 9036, 38, 69, 29, 2056, 70, 26, 71, 1611, 72, 38, 25, 6030, 21, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 273, 24153, 9060, 31, 203, 565, 2254, 5034, 1071, 312, 474, 5147, 273, 374, 18, 3600, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 943, 23164, 273, 576, 31, 203, 203, 565, 1426, 1071, 4075, 5349, 3896, 31, 203, 565, 1426, 1071, 767, 1403, 5349, 30746, 3896, 31, 203, 565, 1426, 1071, 1071, 30746, 3896, 31, 203, 565, 1426, 1071, 8586, 31, 203, 203, 565, 1731, 1578, 3238, 681, 2375, 31, 203, 565, 1731, 1578, 3238, 22128, 18927, 2375, 31, 203, 565, 1731, 1578, 3238, 10734, 2375, 31, 203, 565, 1731, 1578, 3238, 767, 1403, 298, 2375, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 312, 474, 2 ]
pragma solidity ^0.4.23; /* solhint-disable */ import './Project.sol'; contract Blockfund { address[] private projects; address private admin; // Events for notifying gui clients about updates event NewProjectAdded (address contractAddress); constructor() public { admin = msg.sender; } modifier adminOnly() { if (msg.sender == admin) { _; } } function getAllExistingProjects() public view returns (address[]) { return projects; } function getBlockfundAdmin() public view returns (address) { return admin; } // Create a new Blockfund-Project and add it to the project-array function createNewProject( string name, string shortDescription, string longDescription, uint duration, uint goal ) public returns (Project) { Project newProject = new Project(name, shortDescription, longDescription, duration, goal, msg.sender); projects.push(newProject); emit NewProjectAdded(newProject); return newProject; } }
Events for notifying gui clients about updates
contract Blockfund { address[] private projects; address private admin; event NewProjectAdded (address contractAddress); constructor() public { admin = msg.sender; } modifier adminOnly() { if (msg.sender == admin) { _; } } modifier adminOnly() { if (msg.sender == admin) { _; } } function getAllExistingProjects() public view returns (address[]) { return projects; } function getBlockfundAdmin() public view returns (address) { return admin; } function createNewProject( string name, string shortDescription, string longDescription, uint duration, uint goal ) public returns (Project) { Project newProject = new Project(name, shortDescription, longDescription, duration, goal, msg.sender); projects.push(newProject); emit NewProjectAdded(newProject); return newProject; } }
888,756
[ 1, 3783, 364, 5066, 310, 13238, 7712, 2973, 4533, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3914, 74, 1074, 288, 203, 203, 565, 1758, 8526, 3238, 10137, 31, 203, 565, 1758, 3238, 3981, 31, 203, 565, 871, 1166, 4109, 8602, 261, 2867, 6835, 1887, 1769, 203, 203, 203, 225, 3885, 1435, 1071, 288, 203, 565, 3981, 273, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 203, 225, 9606, 3981, 3386, 1435, 288, 203, 565, 309, 261, 3576, 18, 15330, 422, 3981, 13, 288, 203, 1377, 389, 31, 203, 565, 289, 203, 225, 289, 203, 203, 203, 225, 9606, 3981, 3386, 1435, 288, 203, 565, 309, 261, 3576, 18, 15330, 422, 3981, 13, 288, 203, 1377, 389, 31, 203, 565, 289, 203, 225, 289, 203, 203, 203, 225, 445, 5514, 9895, 15298, 1435, 1071, 1476, 1135, 261, 2867, 63, 5717, 288, 203, 565, 327, 10137, 31, 203, 225, 289, 203, 203, 225, 445, 11902, 74, 1074, 4446, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 565, 327, 3981, 31, 203, 225, 289, 203, 203, 225, 445, 15291, 4109, 12, 203, 565, 533, 508, 16, 203, 565, 533, 3025, 3291, 16, 203, 565, 533, 1525, 3291, 16, 203, 565, 2254, 3734, 16, 203, 565, 2254, 17683, 203, 225, 262, 1071, 1135, 261, 4109, 13, 288, 203, 1377, 5420, 394, 4109, 273, 394, 5420, 12, 529, 16, 3025, 3291, 16, 1525, 3291, 16, 3734, 16, 17683, 16, 1234, 18, 15330, 1769, 203, 1377, 10137, 18, 6206, 12, 2704, 4109, 1769, 203, 1377, 3626, 1166, 4109, 8602, 12, 2704, 4109, 1769, 203, 1377, 327, 394, 4109, 31, 203, 225, 289, 203, 2 ]
./full_match/1/0xc297BfaDC872dBc4B77dDB2D894dAF756abC4b1c/sources/Users/eddyoc/development/crypto-mint/src/contracts/EPRCollection.sol
Ensure the coin exists Only the token owner may invoke Token must be funded
function disallowBuy(uint256 _tokenId) external { confirmTokenExists(_tokenId); confirmTokenOwner(_tokenId); confirmTokenFunded(_tokenId); Coin storage _coin = coins[_tokenId]; _coin.price = uint256(0); _coin.forSale = false; emit OffMarket(_tokenId); }
2,998,548
[ 1, 12512, 326, 13170, 1704, 5098, 326, 1147, 3410, 2026, 4356, 3155, 1297, 506, 9831, 785, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 29176, 38, 9835, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 288, 203, 565, 6932, 1345, 4002, 24899, 2316, 548, 1769, 203, 565, 6932, 1345, 5541, 24899, 2316, 548, 1769, 203, 565, 6932, 1345, 42, 12254, 24899, 2316, 548, 1769, 203, 203, 565, 28932, 2502, 389, 12645, 273, 276, 9896, 63, 67, 2316, 548, 15533, 203, 565, 389, 12645, 18, 8694, 273, 2254, 5034, 12, 20, 1769, 203, 565, 389, 12645, 18, 1884, 30746, 273, 629, 31, 203, 203, 565, 3626, 15837, 3882, 278, 24899, 2316, 548, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
claimers[0xEB079Ee381FC821B809F6110cCF7a8439C7A6870] = 0; // seq: 0 -> tkn_id: 0 claimers[0xcBD56A71a02fA7AA01bF1c94c0AeB2828Bebdc0A] = 1; // seq: 1 -> tkn_id: 1 claimers[0x9E1fDAB0FE4141fe269060f098bc7076d248cE7B] = 2; // seq: 2 -> tkn_id: 2 claimers[0x33aEA8f43D9685683b236B20a1818aFcD48204cD] = 3; // seq: 3 -> tkn_id: 3 claimers[0xFD289c26cEF8BB89A76252d9F4617cf54ce4EeBD] = 4; // seq: 4 -> tkn_id: 4 claimers[0x04bfcB7b6bc81361F14c1E2C7592d712e3b9f456] = 5; // seq: 5 -> tkn_id: 5 claimers[0x47E51859134f7d7F7379B1AEcD17a19924025A10] = 6; // seq: 6 -> tkn_id: 6 claimers[0x557159300478941E61cb60A46340F8100C590A56] = 7; // seq: 7 -> tkn_id: 7 claimers[0x7Ed273A361D6bb16833f0E563C313e205738112f] = 8; // seq: 8 -> tkn_id: 8 claimers[0x010594cA1B98ffEd9dFE3d15b749f8BaE3F21C1B] = 9; // seq: 9 -> tkn_id: 9 claimers[0x27221550A0ab5487e79460cd80C3E2aFDB48134e] = 10; // seq: 10 -> tkn_id: 10 claimers[0xF3920288e9DCCFED1AE5a05E466d5da2289062FC] = 11; // seq: 11 -> tkn_id: 11 claimers[0x8dca66E74007d8aD89aFC399d131030Ef29311eF] = 12; // seq: 12 -> tkn_id: 12 claimers[0x355B8F6059F5414AB1F69FcA34088c4aDC554B7f] = 13; // seq: 13 -> tkn_id: 13 claimers[0x020BE4338B750B85c73E598bF468E505A8eb76Ea] = 14; // seq: 14 -> tkn_id: 14 claimers[0x04B00a9F997799F4e265D8796a5F2d22C7A8b9AD] = 15; // seq: 15 -> tkn_id: 15 claimers[0xf8ab6312272E4f2eAB48ddcbD00D905e0E1bCb55] = 16; // seq: 16 -> tkn_id: 16 claimers[0x6B745dEfEE931Ee790DFe5333446eF454c45D8Cf] = 17; // seq: 17 -> tkn_id: 17 claimers[0xE770748e5781f171a0364fbd013188Bc0b33E72f] = 18; // seq: 18 -> tkn_id: 18 claimers[0xEa07596132df9F23Af112593dF0C27A0275d67E5] = 19; // seq: 19 -> tkn_id: 19 claimers[0xB22E58d1550D984b580c564E1dE7868521150988] = 20; // seq: 20 -> tkn_id: 20 claimers[0xf6EA8168a1D1D5d36f22436ad2030d397a616619] = 21; // seq: 21 -> tkn_id: 21 claimers[0x424E9cC4c00aD160c3f36b5471514a6C36a8d73e] = 22; // seq: 22 -> tkn_id: 22 claimers[0x365F34a3236c00823C7844885Ac6BF7a15430eD2] = 23; // seq: 23 -> tkn_id: 23 claimers[0x333C5dBa8179822056F2289BdeDe1B53A863F577] = 24; // seq: 24 -> tkn_id: 24 claimers[0xC9de959443935C3f3CC8E82889d5E80e8cD4a8a9] = 25; // seq: 25 -> tkn_id: 25 claimers[0xE2853A8Ba2e42e78cF8a6b063056F067307fB8f4] = 26; // seq: 26 -> tkn_id: 26 claimers[0xE8926AeBb36A046858D882309e7Aea367F8DB6Cd] = 27; // seq: 27 -> tkn_id: 27 claimers[0x7A48401B0543573D21dfEf15FC54a3E2F599CddF] = 28; // seq: 28 -> tkn_id: 28 claimers[0xd789A1a081553AF9407572711c1163F8A06b4d8F] = 29; // seq: 29 -> tkn_id: 29 claimers[0x498E96c727700a6B7aC2c4EfBd3E9a5DA4F0d137] = 30; // seq: 30 -> tkn_id: 30 claimers[0x7450Cc1b710Afd9B07EECAA19520735e1848479f] = 31; // seq: 31 -> tkn_id: 31 claimers[0x8637576EbDF8b8cb96de6a32C99cb8bDa61d2A11] = 32; // seq: 32 -> tkn_id: 32 claimers[0x77724E749eFB937CE0a78e16E1f1ec5979Cba55a] = 33; // seq: 33 -> tkn_id: 33 claimers[0x3b3D3491f9aE5125f156abA9380aFf62c201054C] = 34; // seq: 34 -> tkn_id: 34 claimers[0x782E60F18e4a3Fc21FF1409d4312ed769f70B1ef] = 35; // seq: 35 -> tkn_id: 35 claimers[0x05C4C65873473C13741c31De2d74005832A0A3d8] = 36; // seq: 36 -> tkn_id: 36 claimers[0xC5E57C099Ed08c882ea1ddF42AFf653e31Ac40df] = 37; // seq: 37 -> tkn_id: 37 claimers[0xe0dC972a92f3b463b43aB29b4F9C960983Bf948F] = 38; // seq: 38 -> tkn_id: 38 claimers[0x4348d40ee12932Aaf0e3412a3aC0598Eb22b96Ad] = 39; // seq: 39 -> tkn_id: 39 claimers[0x75Df0A4a6994AEAa458cfB15863131448fAeDf62] = 40; // seq: 40 -> tkn_id: 40 claimers[0x355e03d40211cc6b6D18ce52278e91566fF29839] = 41; // seq: 41 -> tkn_id: 41 claimers[0x9256EBe5cBcc67E28E2Cd981b835e02590aae7e4] = 42; // seq: 42 -> tkn_id: 42 claimers[0xFf0bAF087F2EE3BbcD2b8aA6560bd5B8F23D99B4] = 43; // seq: 43 -> tkn_id: 43 claimers[0x044bBDc90E1770abD48B6Ede37430b325B6A95EE] = 44; // seq: 44 -> tkn_id: 44 claimers[0x7060FE99b67e37c5fdA833edFe6135580876B996] = 45; // seq: 45 -> tkn_id: 45 claimers[0xaBfc1b7AFD818E1a44539b1EC5021C649b9Dded0] = 46; // seq: 46 -> tkn_id: 46 claimers[0xeec2f0f93e6BC7d13c5E61887aea39d233A0631f] = 47; // seq: 47 -> tkn_id: 47 claimers[0xF6d670C5C0B206f44E93dE811054F8C0b6e15905] = 48; // seq: 48 -> tkn_id: 48 claimers[0x679959449b608AF08d9419fE66D4e985c7d64D96] = 49; // seq: 49 -> tkn_id: 49 claimers[0xF5Dc9930f10Ca038De87C2FDdebe03C10aDeABDC] = 50; // seq: 50 -> tkn_id: 50 claimers[0x07587c046d4d4BD97C2d64EDBfAB1c1fE28A10E5] = 51; // seq: 51 -> tkn_id: 51 claimers[0xc674fFaD8082Aa238F15cd5a91aB1fd68aFEcEaE] = 52; // seq: 52 -> tkn_id: 52 claimers[0xF670B0Ce50B31B5BE40fD8cE84535a7D021775EF] = 53; // seq: 53 -> tkn_id: 53 claimers[0xEec4013a607D720989DB8F464361CdcF2cb7A7BD] = 54; // seq: 54 -> tkn_id: 54 claimers[0xA183B2f9d89367D935EC1Ebd1d33288a7113a971] = 55; // seq: 55 -> tkn_id: 55 claimers[0x42de824dA4C1Af884ebEdaA2352Fd4d4e00445DF] = 56; // seq: 56 -> tkn_id: 56 claimers[0x6F4440719569D61571f50c7e2B33b17E191b0654] = 57; // seq: 57 -> tkn_id: 57 claimers[0xBe671d9b29F218d711404D8F39f830eE14dAAF72] = 58; // seq: 58 -> tkn_id: 58 claimers[0xC7892093FEE029bF01D2b8C02098Cd4864bE3939] = 59; // seq: 59 -> tkn_id: 59 claimers[0x5a6541F3205D510ddB3B6dFD7b5fc5361C6fD47c] = 60; // seq: 60 -> tkn_id: 60 claimers[0xcBde85bF0b88791f902d4c18E4ad5F5CFAf76794] = 61; // seq: 61 -> tkn_id: 61 claimers[0x6A6181794DDDC287F54CF7393d81539Be2899cFd] = 62; // seq: 62 -> tkn_id: 62 claimers[0x70A2907B45A81f53b09976294B99b345B77fD134] = 63; // seq: 63 -> tkn_id: 63 claimers[0x171c3eEd74fcd74881f8Cb1de048C156D8c0EdE4] = 64; // seq: 64 -> tkn_id: 64 claimers[0x9d430D7338FF1E15f889ac90Ca992630F5150e64] = 65; // seq: 65 -> tkn_id: 65 claimers[0xd2C8CC3DcB9C79A4F85Bcad9EF4e0ccf4619d690] = 66; // seq: 66 -> tkn_id: 66 claimers[0x4e79317de3479dC23De1F1A9Ca664651bCAc8A43] = 67; // seq: 67 -> tkn_id: 67 claimers[0x35dF3706eD8779Fc4b401722754867304c11c95D] = 68; // seq: 68 -> tkn_id: 68 claimers[0xD29D862f28331705D432Dfab3f3491372E7295ad] = 69; // seq: 69 -> tkn_id: 69 claimers[0x889769e73f452E10B70414917c4d1fcd0F9a53b8] = 70; // seq: 70 -> tkn_id: 70 claimers[0x8a381C0bB4B2322a455897659cb34BC1395d3124] = 71; // seq: 71 -> tkn_id: 71 claimers[0x5319C3F016C7FC4b6770d4a8C313036da7F61290] = 72; // seq: 72 -> tkn_id: 72 claimers[0xC9D15F4E6f1b37CbF0E8068Ff84B5282edEF9707] = 73; // seq: 73 -> tkn_id: 73 claimers[0x826121D2a47c9D6e71Fd4FED082CECCc8A5381b1] = 74; // seq: 74 -> tkn_id: 74 claimers[0xb12F75B5F95022a54E6BbDd1086691635571911e] = 75; // seq: 75 -> tkn_id: 75 claimers[0xc9C56009DD643c2e6567E83F75A69C8Cc29AdeaC] = 76; // seq: 76 -> tkn_id: 76 claimers[0x40e00884ee94a5143cd9419d5DCA7Ede6730a793] = 77; // seq: 77 -> tkn_id: 77 claimers[0x78F3Aab3E918F2Bf8089EBC3698f78D3a273D6B2] = 78; // seq: 78 -> tkn_id: 78 claimers[0x7e6A5192cF2033c00efA844A353AFE1869bDF94B] = 79; // seq: 79 -> tkn_id: 79 claimers[0x3af46de2aCc78D4d4902a87618d28C0B194d7e63] = 80; // seq: 80 -> tkn_id: 80 claimers[0x0c84d74104Ac83AB98a80FB5e88F06137e842825] = 81; // seq: 81 -> tkn_id: 81 claimers[0x54280007118299877b466875B2aa6B59327DD93c] = 82; // seq: 82 -> tkn_id: 82 claimers[0x26122FE0a9966f1fA4897982782225037B3e490B] = 83; // seq: 83 -> tkn_id: 83 claimers[0xaCcE74f9dD9f3133f160417A8B554CD3Cc8a3B95] = 84; // seq: 84 -> tkn_id: 84 claimers[0xb081c44e699A895f126D09D362B1088826D12963] = 85; // seq: 85 -> tkn_id: 85 claimers[0x86c8283764C402C9E61d916096780014724C8fC9] = 86; // seq: 86 -> tkn_id: 86 claimers[0xC7857556C226b0e61bb18EB8Dd191bE7E1ee8Ad3] = 87; // seq: 87 -> tkn_id: 87 claimers[0xc45e08A07F491e778463460D52c592d11C3f761a] = 88; // seq: 88 -> tkn_id: 88 claimers[0x6F08fdC20c018121c6BE83218C95eBf42A45b571] = 89; // seq: 89 -> tkn_id: 89 claimers[0x073859cdA73a56d92a13DbE2B4e0B34dEF4756e8] = 90; // seq: 90 -> tkn_id: 90 claimers[0xA2531843629b036C6691A63bE5a91291902d42E0] = 91; // seq: 91 -> tkn_id: 91 claimers[0x4C697E1432cB49AC229241b5577284671Bae9d16] = 92; // seq: 92 -> tkn_id: 92 claimers[0x5973FFe2B9608e66A328c87c534e4Bb758618e73] = 93; // seq: 93 -> tkn_id: 93 claimers[0xcdB76A96af6eEC323a0fAC36D852b552f16C5a5F] = 94; // seq: 94 -> tkn_id: 94 claimers[0x23D623D3C6F334f55EF0DDF14FF0e05f1c88A76F] = 95; // seq: 95 -> tkn_id: 95 claimers[0x843D261B740F97BF31d09846F9d96dcC5Fd2a0D0] = 96; // seq: 96 -> tkn_id: 96 claimers[0x81cee999e0cf2DA5b420a5c02649C894F69C86bD] = 97; // seq: 97 -> tkn_id: 97 claimers[0x927a03B6606380147e38E88b1B491c7D29a62eEa] = 98; // seq: 98 -> tkn_id: 98 claimers[0x64F8eF34aC5Dc26410f2A1A0e2b4641189040231] = 99; // seq: 99 -> tkn_id: 99 claimers[0x1cFACa65bF36aE4548c9fB84d4d8A22bfBAA7B84] = 100; // seq: 100 -> tkn_id: 100 claimers[0xa069cD30b87e947Ba78e36e30E485e4926e4d176] = 101; // seq: 101 -> tkn_id: 101 claimers[0x9631200833a348641c5D08C5E146BBBFcD5367D2] = 102; // seq: 102 -> tkn_id: 102 claimers[0xb521154e8f8978f64567FE0FA7359Ab47f7363fA] = 103; // seq: 103 -> tkn_id: 103 claimers[0x9b534B88E83013B2fCE9Bb5BA813a6B96707cc8F] = 104; // seq: 104 -> tkn_id: 104 claimers[0xAaC5Ca3FEe00833ACC563FB41048179ACA8b9c07] = 105; // seq: 105 -> tkn_id: 105 claimers[0xeb0f5dce389A86a64c71F91eCE001067A9cD574E] = 106; // seq: 106 -> tkn_id: 106 claimers[0xA735E424fD55a18148BB5FE1f128Fbe30B7b56DB] = 107; // seq: 107 -> tkn_id: 107 claimers[0x85222954e2742ACe2F14f23E7694Ec1AbFD00F49] = 108; // seq: 108 -> tkn_id: 108 claimers[0x601379eF00F1879F13E4b498133b560b06bfeC36] = 109; // seq: 109 -> tkn_id: 109 claimers[0xD0c72d410D06C4C4A70Ff96beaB8432071F4d3B8] = 110; // seq: 110 -> tkn_id: 110 claimers[0xC1c2E49a3223E56f07068d836fd354e7269cBD78] = 111; // seq: 111 -> tkn_id: 111 claimers[0x88bf9430fE41AC4Dd87BeC4ba3C44012f7876e55] = 112; // seq: 112 -> tkn_id: 112 claimers[0xB8F69EC91b068E702BafCBf282feca36c585a539] = 113; // seq: 113 -> tkn_id: 113 claimers[0x6E03a79F43A6bd3b77531603990e9b39456389Ed] = 114; // seq: 114 -> tkn_id: 114 claimers[0xf522F0672107333dC549A8AcEDF62746844b65ce] = 115; // seq: 115 -> tkn_id: 115 claimers[0x4A74407858aeF6532ed771cFBb154829c53ABc47] = 116; // seq: 116 -> tkn_id: 116 claimers[0xa10e13c392EBB57adD9f23aa3792ac05D0d6dE7E] = 117; // seq: 117 -> tkn_id: 117 claimers[0xB0C054B2F0CA15fEadD4172037dC1e93b113AcC9] = 118; // seq: 118 -> tkn_id: 118 claimers[0xdC30CABcfBD95Ea2D5675002B5b00a2C499FAc12] = 119; // seq: 119 -> tkn_id: 119 claimers[0xc6c1E852ECCE4Ce5a0C93F0E68063202dA81202b] = 120; // seq: 120 -> tkn_id: 120 claimers[0x9cf39Ad673E95F292CD2060A36AE552227198a0C] = 121; // seq: 121 -> tkn_id: 121 claimers[0xbE20DFb456b7E81f691A8445d073e56602E3cefa] = 122; // seq: 122 -> tkn_id: 122 claimers[0xb29D3652ebe85C4303c87d3B728C511c4b0943E3] = 123; // seq: 123 -> tkn_id: 123 claimers[0x8CFAb48f1B6328eEAF6abaFa5Ba780550bC5109D] = 124; // seq: 124 -> tkn_id: 124 claimers[0x26cF22300E6B89437e7EEc90Bf56CadDBF4bB322] = 125; // seq: 125 -> tkn_id: 125 claimers[0x9B39dadCD266337e8F7C91dCA03fF61484a8882b] = 126; // seq: 126 -> tkn_id: 126 claimers[0x3E5e35208a84eF21d441a5365BE09BF65Af2f709] = 127; // seq: 127 -> tkn_id: 127 claimers[0x630098B792120d38dF22ecE88378d0676A3ce48c] = 128; // seq: 128 -> tkn_id: 128 claimers[0x70c5d2942b12C0aa6103129B18B3503c0610408e] = 129; // seq: 129 -> tkn_id: 129 claimers[0x91Fa472FB12Ef104d649facCE00e3bA43dE57A8D] = 130; // seq: 130 -> tkn_id: 130 claimers[0xCA755A9bD26148F18B4D2e316966E9fE915d46aC] = 131; // seq: 131 -> tkn_id: 131 claimers[0x6d6AB746901f8F7de018DCc417b6D417725B41aF] = 132; // seq: 132 -> tkn_id: 132 claimers[0x42a2D911F4C526233F203D2d156Aa5146044cB7e] = 133; // seq: 133 -> tkn_id: 133 claimers[0x0B01fE5189d95c0fa890fd6b431928B5dF58D027] = 134; // seq: 134 -> tkn_id: 134 claimers[0x84b8bfD62Bb591976429dC060ABd9bfD0eD6508B] = 135; // seq: 135 -> tkn_id: 135 claimers[0xe0d30e989810470A74Ab2D7EBaD424d76FFA8cdd] = 136; // seq: 136 -> tkn_id: 136 claimers[0x390b07DC402DcFD54D5113C8f85d90329A0141ef] = 137; // seq: 137 -> tkn_id: 137 claimers[0xfbF30C01041A372Be48217FE201a30470b0b3Ac2] = 138; // seq: 138 -> tkn_id: 138 claimers[0x973b79656F9A2B6d3F9B04E93F3C340C9f7b4C6C] = 139; // seq: 139 -> tkn_id: 139 claimers[0xDf5B7bE800A5A7A67e887C2f677Cd29a7a05b6E1] = 140; // seq: 140 -> tkn_id: 140 claimers[0x3720c491F4564429154862285E7F1f830E059065] = 141; // seq: 141 -> tkn_id: 141 claimers[0x6046D412B45dACe6c963C7c3C892AD951EC97e57] = 142; // seq: 142 -> tkn_id: 142 claimers[0x4b4E4A8bCB923783A401dc80766D7aBf5631dC0d] = 143; // seq: 143 -> tkn_id: 143 claimers[0x4460dD70a847481f63e015b689a9E226E8bD5b71] = 144; // seq: 144 -> tkn_id: 144 claimers[0x7d2D2E04f1Db8B54746eFA719CB62F32A6C84a84] = 145; // seq: 145 -> tkn_id: 145 claimers[0xdFA56E55811b6F9548F4cB876CC796a6A4071993] = 146; // seq: 146 -> tkn_id: 146 claimers[0xceCb7E46Ed153BfC38961b27Da43f8fddCbEF210] = 147; // seq: 147 -> tkn_id: 147 claimers[0xCffA068214d25B3D75f4676302C0E9390cCBBbEb] = 148; // seq: 148 -> tkn_id: 148 claimers[0x0873E406b948314E516eF6B6C618ba42B72b46C6] = 149; // seq: 149 -> tkn_id: 149 claimers[0xdC67aF6B6Ee64eec179135103b62FB68360Af860] = 150; // seq: 150 -> tkn_id: 150 claimers[0xDB7b6AA8240f527c35FD8E8c5e3a9eFc7359341d] = 151; // seq: 151 -> tkn_id: 151 claimers[0xF962e687562999a127a5b5A2ECBE99d0601564Eb] = 152; // seq: 152 -> tkn_id: 152 claimers[0x6Fa98A4254c7E9Ec681cCeb3Cb8D64a70Dbea256] = 153; // seq: 153 -> tkn_id: 153 claimers[0x5EFACb9C824eb8b0acE54a0054B7924e6c9eFaf0] = 154; // seq: 154 -> tkn_id: 154 claimers[0xaB59d30a5CE7cD360Cc333235a1deA7e3Ba3f2a1] = 155; // seq: 155 -> tkn_id: 155 claimers[0x8f1b33E27b6135BFC87Cda27Ebc90025f039F5fe] = 156; // seq: 156 -> tkn_id: 156 claimers[0x49e03A6C22602682B3Fbecc5B181F7649b1DB6Ad] = 157; // seq: 157 -> tkn_id: 157 claimers[0x0A3e7c501d685dcc9d65119e3f3A9f8F4875f8F6] = 158; // seq: 158 -> tkn_id: 158 claimers[0x2fb0d4F09e5F7E399354D8DbF602c871b84c081F] = 159; // seq: 159 -> tkn_id: 159 claimers[0xe2D18861c892f4eFbaB6b2749e2eDe16aF458A94] = 160; // seq: 160 -> tkn_id: 160 claimers[0x03aEC62437E9f1485410654E5daf4f5ad707f395] = 161; // seq: 161 -> tkn_id: 161 claimers[0xB7493191Dbf9f687D3e019cDaaDc3C52d95C87EF] = 162; // seq: 162 -> tkn_id: 162 claimers[0x6F6ed604bc1A64a385978c99310D2fc0758AF29e] = 163; // seq: 163 -> tkn_id: 163 claimers[0xF9A508D543416f530295048985e7a7C295b7F957] = 164; // seq: 164 -> tkn_id: 164 claimers[0xfB89fBaFE753873386D6E46dB066c47d8Ef857Fa] = 165; // seq: 165 -> tkn_id: 165 claimers[0xF81d36Dd1406f937323aC6C43F1be8D3b5Fd8d30] = 166; // seq: 166 -> tkn_id: 166 claimers[0x88591bc3054339708bA101116E04f0359232962F] = 167; // seq: 167 -> tkn_id: 167 claimers[0xC707b5BD687749e7e418eBDd79a387904025B02e] = 168; // seq: 168 -> tkn_id: 168 claimers[0x2cBC074df0dC03defDd1d3D985B4B1a961DB5415] = 169; // seq: 169 -> tkn_id: 169 claimers[0xf4BD7C08403250BeE1fD9D819d9DF0Ae956C3ceb] = 170; // seq: 170 -> tkn_id: 170 claimers[0x442670b5f713c61Eb9FcB4e27fcA6505815c9861] = 171; // seq: 171 -> tkn_id: 171 claimers[0xBB8135f8136425f7af9De8ee926C58D09E9525eE] = 172; // seq: 172 -> tkn_id: 172 claimers[0x5e0819Db5c0b3952149150310945752ae22745B0] = 173; // seq: 173 -> tkn_id: 173 claimers[0x3d359BE336fa4760d4399230F4067e04D1b9ed7B] = 174; // seq: 174 -> tkn_id: 174 claimers[0x136BE67011Dd5F97dcdba8d0F3b5B650aCdcaE5C] = 175; // seq: 175 -> tkn_id: 175 claimers[0x24f39151D6d8A9574D1DAC49a44F1263999D0dda] = 176; // seq: 176 -> tkn_id: 176 claimers[0x1c458B84B81B5Cc1ed226c05873E75e2Ae1dCA90] = 177; // seq: 177 -> tkn_id: 177 claimers[0xFab6e024A48d1d56D3A030E9ecC6f17F3122fB73] = 178; // seq: 178 -> tkn_id: 178 claimers[0x47b0A090Ea0D040F65F3f2Ab0fFc7824C924E144] = 179; // seq: 179 -> tkn_id: 179 claimers[0xAd2D729Ad42373A3cad2ef405197E2550f4af860] = 180; // seq: 180 -> tkn_id: 180 claimers[0x62cfc31f574F8ec9719d719709BCCE9866BEcaCd] = 181; // seq: 181 -> tkn_id: 181 claimers[0xe6BB1bEBF6829ca5240A80F7076E4CFD6Ee540ae] = 182; // seq: 182 -> tkn_id: 182 claimers[0x94d3B13745c23fB57a9634Db0b6e4f0d8b5a1053] = 183; // seq: 183 -> tkn_id: 183 claimers[0x1eF576f02107BEc448d74DcA749964013A8531e7] = 184; // seq: 184 -> tkn_id: 184 claimers[0x9b2D76f2E5E92b2C78C6e2ce07c6f86B95091964] = 185; // seq: 185 -> tkn_id: 185 claimers[0x06e9f7674a2cC609adA8dc6777f07385A238006a] = 186; // seq: 186 -> tkn_id: 186 claimers[0xC5b09ee88Cfb4FF08C8769A89B0c314FC1636b19] = 187; // seq: 187 -> tkn_id: 187 claimers[0x6595cfA52F9F91bA319386c4549039581259D57A] = 188; // seq: 188 -> tkn_id: 188 claimers[0x06B40D42b10ADBEa8CA0f12Db1E6E1e11632EB0d] = 189; // seq: 189 -> tkn_id: 189 claimers[0x98a784132CF101E8Cd2764ded4c2F246325F1fe6] = 190; // seq: 190 -> tkn_id: 190 claimers[0x693Ab9656C70BfA41443A84d4c96eAFb82d382B4] = 191; // seq: 191 -> tkn_id: 191 claimers[0xBC0147233b8a028Ed4fbcEa6CF473e30EdcfabD3] = 192; // seq: 192 -> tkn_id: 192 claimers[0xd6fE3581974330145d703B1914a6A441512992A7] = 193; // seq: 193 -> tkn_id: 193 claimers[0x935016109bFA23F810112F5Fe2862cB0c5F26bd2] = 194; // seq: 194 -> tkn_id: 194 claimers[0x2E5F97Ce8b95Ffb5B007DA1dD8fE0399679a6F23] = 195; // seq: 195 -> tkn_id: 195 claimers[0xF0fE8DA6C23c4772455F49102947157A56d22C76] = 196; // seq: 196 -> tkn_id: 196 claimers[0x03890EeB6303C86A4b44218Fbe8e8811fab0CB43] = 197; // seq: 197 -> tkn_id: 197 claimers[0x6A2e363b31D5fd9556765C8f37C1ddd2Cd480fA3] = 198; // seq: 198 -> tkn_id: 198 claimers[0x4744e7077Cf68Bca4feFFc42f3E8C1dbDF59CBaa] = 199; // seq: 199 -> tkn_id: 199 claimers[0xcEa283786F5f676d9A63599AF98D850eFEB95BaD] = 200; // seq: 200 -> tkn_id: 200 claimers[0xcb1C261dc5EF5D611c7E2F83653eA0e744654089] = 201; // seq: 201 -> tkn_id: 201 claimers[0x970393Db17dde3b234A4C17D2Be2Bad3A34249f7] = 202; // seq: 202 -> tkn_id: 202 claimers[0x84414ef56970b4F6B44673cdeC093cEE916Ad471] = 203; // seq: 203 -> tkn_id: 203 claimers[0x237b3c12D93885b65227094092013b2a792e92dd] = 204; // seq: 204 -> tkn_id: 204 claimers[0x611b3f03fc28Eb165279eADeaB258388D125e8BC] = 205; // seq: 205 -> tkn_id: 205 claimers[0x20DC3e9ECcc11075A055Aa631B64aF4b0d6dc571] = 206; // seq: 206 -> tkn_id: 206 claimers[0x5703Cf5FCE210caA2dbbFB6e88B77d126683fA76] = 207; // seq: 207 -> tkn_id: 207 claimers[0x1850AB1344493b8f66a0780c6806fe57AE7a13B4] = 208; // seq: 208 -> tkn_id: 208 claimers[0x710A169B822Bf51b8F8E6538c63deD200932BB29] = 209; // seq: 209 -> tkn_id: 209 claimers[0xA37EDEE06096F9fbA272B4943066fcd28d39Dc2d] = 210; // seq: 210 -> tkn_id: 210 claimers[0xb42FeE033AD3809cf9D1d6C1f922478F1C4A652c] = 211; // seq: 211 -> tkn_id: 211 claimers[0xebfc11fE400f2DF40B8b669845d4A3479192e859] = 212; // seq: 212 -> tkn_id: 212 claimers[0xf18210B928bc3CD75966329429131a7fD6D1b667] = 213; // seq: 213 -> tkn_id: 213 claimers[0x24d32644137e2Bc36f3d039977C83e5cD489F809] = 214; // seq: 214 -> tkn_id: 214 claimers[0x99dcfb0E41BEF20Dc9661905D4ABBD92267095Ee] = 215; // seq: 215 -> tkn_id: 215 claimers[0x1e390D5391B98F3a2d489F1a7CA646F8F336491C] = 216; // seq: 216 -> tkn_id: 216 claimers[0xBECb82002565aa5C6c4722A473AdDb5e2c909f9C] = 217; // seq: 217 -> tkn_id: 217 claimers[0x721D12Fc93F4E6509D388BF79EcE34CDcB775d62] = 218; // seq: 218 -> tkn_id: 218 claimers[0x108fF5724eC28D6066855899c4a422De4E0ae6a2] = 219; // seq: 219 -> tkn_id: 219 claimers[0x44e02B37c29d3689d95Df1C87e6153CC7e2609AA] = 220; // seq: 220 -> tkn_id: 220 claimers[0x41e309Fb027372e28907c0FCAD78DD26460Dd4c2] = 221; // seq: 221 -> tkn_id: 221 claimers[0xb827857235d4eACc540A79e9813c80E351F0dC06] = 222; // seq: 222 -> tkn_id: 222 claimers[0x8e27ac9EA29ecFfC575BbC73502D3c18848e57a0] = 223; // seq: 223 -> tkn_id: 223 claimers[0x4Fa0DE7b23BcF1e8714E0c91f7B856e5Ff99c6D0] = 224; // seq: 224 -> tkn_id: 224 claimers[0x8f6869697ab3ee78C3480D3D36B112025373438C] = 225; // seq: 225 -> tkn_id: 225 claimers[0x20fac303520CB60860065871FA213DE09D10A009] = 226; // seq: 226 -> tkn_id: 226 claimers[0x61603cD19B067B417284cf9fC94B3ebF5703824a] = 227; // seq: 227 -> tkn_id: 227 claimers[0x468769E894f0894A44B50AE363395793b17F11b3] = 228; // seq: 228 -> tkn_id: 228 claimers[0xE797B7d15f06733b9ceCF87656aD5f56945A1eBf] = 229; // seq: 229 -> tkn_id: 229 claimers[0x6592aB22faD2d91c01cCB4429F11022E2595C401] = 230; // seq: 230 -> tkn_id: 230 claimers[0x68cf193fFE134aD92C1DB0267d2062D01FEFDD06] = 231; // seq: 231 -> tkn_id: 231 claimers[0x7988E3ae0d19Eff3c8bC567CA0438F6Df3cB2813] = 232; // seq: 232 -> tkn_id: 232 claimers[0xd85bCc93d3A3E89303AAaF43c58E624D24160455] = 233; // seq: 233 -> tkn_id: 233 claimers[0xc34F0F4cf2ffD0F91DB7DFBd81B432580019F1a8] = 234; // seq: 234 -> tkn_id: 234 claimers[0xbf9fe0f5cAeE6967C874e108fE69969E09fa156c] = 235; // seq: 235 -> tkn_id: 235 claimers[0x1eE73ad65581d5Efe7430dcb5a653d5015332454] = 236; // seq: 236 -> tkn_id: 236 claimers[0xFfcef83Eb7Dd0Ec7770Ac08D8f11a87fA87E12d9] = 237; // seq: 237 -> tkn_id: 237 claimers[0x6Acb64A76e62D433a9bDCB4eeA8343Be8b3BeF48] = 238; // seq: 238 -> tkn_id: 238 claimers[0x8eCAD8Da3D1F5E0E91e8A55dd979A863CFdFCee7] = 239; // seq: 239 -> tkn_id: 239 claimers[0x572f60c0b887203324149D9C308574BcF2dfaD82] = 240; // seq: 240 -> tkn_id: 240 claimers[0xcCf70d7637AEbF9D0fa22e542Ac4082569f4ED5A] = 241; // seq: 241 -> tkn_id: 241 claimers[0x9de35B6bE7B911DEA9A4DE84E9b8a34038c6ECea] = 242; // seq: 242 -> tkn_id: 242 claimers[0x1c05141A1A0d425E92653ADfefDaFaec40681bdB] = 243; // seq: 243 -> tkn_id: 243 claimers[0x79Bc1a648aa95618bBeB3BFb2a15E3415C52FF86] = 244; // seq: 244 -> tkn_id: 244 claimers[0x5f3E1bf780cA86a7fFA3428ce571d4a6D531575D] = 245; // seq: 245 -> tkn_id: 245 claimers[0xcD426623A98E22e76758a98F7A85d4499973b37F] = 246; // seq: 246 -> tkn_id: 246 claimers[0x674901AdeB413C126a069402E751ba80F2e2152e] = 247; // seq: 247 -> tkn_id: 247 claimers[0x111f5B33389BBA60c3b16a6ae891F7D281762369] = 248; // seq: 248 -> tkn_id: 248 claimers[0x51679136e1a3407912f8fA131Bc5F611c52d9fEe] = 249; // seq: 249 -> tkn_id: 249 claimers[0xB955E56849E0875E44074C56F21CF009E2B8B6c4] = 250; // seq: 250 -> tkn_id: 250 claimers[0x3D7af9ABecFe6BdD60C8dcDFaF3b83f92DB06885] = 251; // seq: 251 -> tkn_id: 251 claimers[0x836B55F9A4A39f5b39b372a0943C782cE48C0Ef8] = 252; // seq: 252 -> tkn_id: 252 claimers[0x6412dDF748608073034090646D37D5E4CE71a4CE] = 253; // seq: 253 -> tkn_id: 253 claimers[0x924fD2357ACe38052C5f73c0bFDCd2666b02F908] = 254; // seq: 254 -> tkn_id: 254 claimers[0xFA3C94ab4Ba1fD92bf8331C7cC6aabe50074D08D] = 255; // seq: 255 -> tkn_id: 255 claimers[0xE75a37358127B089Ae9E2E23322E23bAE28ea3D9] = 256; // seq: 256 -> tkn_id: 256 claimers[0xA2Eef2A6EB56118C910101d53a860F62cf2Ec903] = 257; // seq: 257 -> tkn_id: 257 claimers[0xeA83A7a09229F7921D9a72A1f5Ff03aA5bA096E2] = 258; // seq: 258 -> tkn_id: 258 claimers[0xA0C9D9d21b2CB0400D59C70AC6CEA3e7a81F1AA7] = 259; // seq: 259 -> tkn_id: 259 claimers[0x295Cf1759Af15bE4b81D12d6Ee41C3D9A30Ad410] = 260; // seq: 260 -> tkn_id: 260 claimers[0xb8b52400D83e12e61Ea0D00A1fcD7e1E2F8d5f83] = 261; // seq: 261 -> tkn_id: 261 claimers[0x499E5938F54C3769c4208F1Bc58AEAdF13A1FF8B] = 262; // seq: 262 -> tkn_id: 262 claimers[0x2F48e68D0e507AF5a278130d375AA39f4966E452] = 263; // seq: 263 -> tkn_id: 263 claimers[0xCAB03A436F0af91cE68594f45A95D8f7f5004A14] = 264; // seq: 264 -> tkn_id: 264 claimers[0x8ee4219378c25ca2023690A71f2d337a29d67A89] = 265; // seq: 265 -> tkn_id: 265 claimers[0x00737ac98C3272Ee47014273431fE189047524e1] = 266; // seq: 266 -> tkn_id: 266 claimers[0x29175A067860f9BDBDb411dB0A76F5EbDa5544fF] = 267; // seq: 267 -> tkn_id: 267 claimers[0x5bb3e01c8dDCE82AF3f6e76f46d8965176A2daEe] = 268; // seq: 268 -> tkn_id: 268 claimers[0x47F2F66729171D0b40E9fDccAbBae5d8ec2d2065] = 269; // seq: 269 -> tkn_id: 269 claimers[0x86017110100312E0C2cCc0c14A58C4bf830a7EF6] = 270; // seq: 270 -> tkn_id: 270 claimers[0x26ceA6C7a525c17027750d315aBa267b7B0bB209] = 271; // seq: 271 -> tkn_id: 271 claimers[0xa0E609533840b910208BFb4b711df62C4a6247D2] = 272; // seq: 272 -> tkn_id: 272 claimers[0x35570f310697a5C687Eb37b63B4Ae696cE0d14C0] = 273; // seq: 273 -> tkn_id: 273 claimers[0x9e0eD477f110cb75453181Cd4261D40Fa7396056] = 274; // seq: 274 -> tkn_id: 274 claimers[0xd53b873683Df491553eea6a069770144Ad30F3A9] = 275; // seq: 275 -> tkn_id: 275 claimers[0x164934C2A068932b83Bbf81A66FF01825F2dc5e1] = 276; // seq: 276 -> tkn_id: 276 claimers[0x3eC7e5215984bE5FebA858c9502BD563bB135B1a] = 277; // seq: 277 -> tkn_id: 277 claimers[0x587A050489516119D39C228519536b561ff3fA93] = 278; // seq: 278 -> tkn_id: 278 claimers[0x8767149b0520f2e6A56eed33166Ff8484B3Ac058] = 279; // seq: 279 -> tkn_id: 279 claimers[0x49A3f1200730D84551d13FcBC121A6405eDe4D56] = 280; // seq: 280 -> tkn_id: 280 claimers[0xc206014aAf21E07ae5868730098D919F99d79616] = 281; // seq: 281 -> tkn_id: 281 claimers[0x38878917a3EC081c4C78dde8Dd49F43eE10CAf12] = 282; // seq: 282 -> tkn_id: 282 claimers[0x2FfF3F5b8560407781dFCb04a068D7635A179EFE] = 283; // seq: 283 -> tkn_id: 283 claimers[0x56256Df5A901D0B566C1944D4307E2e4Efb23838] = 284; // seq: 284 -> tkn_id: 284 claimers[0x280b8503E2927060120391baf51733E357B190eb] = 285; // seq: 285 -> tkn_id: 285 claimers[0x8C0Da5cc7524Ed8a3f6C79B07aC43081F5A54975] = 286; // seq: 286 -> tkn_id: 286 claimers[0xdE4f8a84929bF5185c03697444D8ddb8ae852116] = 287; // seq: 287 -> tkn_id: 287 claimers[0x8BB01a948ABAC1758E3ED59621f1CD7d90C8FF8C] = 288; // seq: 288 -> tkn_id: 288 claimers[0x59B7759338666625957B1Ef4482DeBd5da1a6091] = 289; // seq: 289 -> tkn_id: 289 claimers[0xD63ba61D2f3C3f108a3C54B987e9435aFB715Cc5] = 290; // seq: 290 -> tkn_id: 290 claimers[0x9f8eF2849133286860A8216cA11359381706Fa4a] = 291; // seq: 291 -> tkn_id: 291 claimers[0x125EaE40D9898610C926bb5fcEE9529D9ac885aF] = 292; // seq: 292 -> tkn_id: 292 claimers[0xB4Ae4070a56624A7c99B438664853D0f454BE116] = 293; // seq: 293 -> tkn_id: 293 claimers[0xb651Ad89b16cca4bD6FE8b4C0Bc3481b15F779c1] = 294; // seq: 294 -> tkn_id: 294 claimers[0x0F193c91a7F3B41Db23d1ab0eeD96003b9f62Ca8] = 295; // seq: 295 -> tkn_id: 295 claimers[0x09A221b474B51e530f20C727d519e243207E128B] = 296; // seq: 296 -> tkn_id: 296 claimers[0x6ea3A5faA3788814262bB1b3a5c0b82d3d24fCA6] = 297; // seq: 297 -> tkn_id: 297 claimers[0xfDf9EAfF221dB644Eb5acCA77Fe72B6553FFbDc9] = 298; // seq: 298 -> tkn_id: 298 claimers[0xb6ccBc7252a4576387d7AF08E603A330950477c5] = 299; // seq: 299 -> tkn_id: 299 claimers[0xB248B3309e31Ca924449fd2dbe21862E9f1accf5] = 300; // seq: 300 -> tkn_id: 300 claimers[0x53d9Bfc075ed4Adb207ed0C95f230A2387Bb001c] = 301; // seq: 301 -> tkn_id: 301 claimers[0x36870b333D653A201d3D7a1209937fE229B7926a] = 302; // seq: 302 -> tkn_id: 302 claimers[0x8A289c7CA7224bEf1Acf234bcD92bF1b8EE5e2D4] = 303; // seq: 303 -> tkn_id: 303 claimers[0xC3aB2C2Eb604F159C842D9cAdaBBa2d6254c43d5] = 304; // seq: 304 -> tkn_id: 304 claimers[0x90C4BF2bd887E0AbC40Fb3f1fAd0d294eBb18146] = 305; // seq: 305 -> tkn_id: 305 claimers[0x0130F60bFe7EA24027eBa9894Dd4dAb331885209] = 306; // seq: 306 -> tkn_id: 306 claimers[0x83c4224A765dEE2Fc903dDed4f9A2046Ba7891E2] = 307; // seq: 307 -> tkn_id: 307 claimers[0xA86CB26efc0Cb9d0aC53a2a56292f4BCDfEa6E1a] = 308; // seq: 308 -> tkn_id: 308 claimers[0x031bE1B4fEe66C3cB66DE265172F3567a6CAb2Eb] = 309; // seq: 309 -> tkn_id: 309 claimers[0x5402C9674B5918B803A2826CCF4CE5af813fCd97] = 310; // seq: 310 -> tkn_id: 310 claimers[0xb14ae50038abBd0F5B38b93F4384e4aFE83b9350] = 311; // seq: 311 -> tkn_id: 311 claimers[0xb200d463bCD09CE93454A394a91573DcDe76Bc28] = 312; // seq: 312 -> tkn_id: 312 claimers[0x3a2C5863e401093F9F994Aa989DDFE5F3a154AbD] = 313; // seq: 313 -> tkn_id: 313 claimers[0x3cB704A5FB4428796b728DF7e4CbC67BCA1497Ae] = 314; // seq: 314 -> tkn_id: 314 claimers[0x9BEcaC41878CA0a280Edd9A6360e3beece1a21Bb] = 315; // seq: 315 -> tkn_id: 315 claimers[0x8a382bb6BF2008492268DEdC549B6Cf189a067B5] = 316; // seq: 316 -> tkn_id: 316 claimers[0x8956CBFB070e6fdf8FF8e94DcEDD665902707Dda] = 317; // seq: 317 -> tkn_id: 317 claimers[0x21B9c3830ef962aFA00e4f45d1618F61Df99C404] = 318; // seq: 318 -> tkn_id: 318 claimers[0x48A6ab900eE882f02649f565419b96C32827E29E] = 319; // seq: 319 -> tkn_id: 319 claimers[0x15041371A7aD0a8a97e5A448804dD33FD8DdE233] = 320; // seq: 320 -> tkn_id: 320 claimers[0xA9786dA5d3ABb6C404b79DF28b7f402E58eF7c5B] = 321; // seq: 321 -> tkn_id: 321 claimers[0xea0Ca6DAF5019935ecd3693688941Bdbd4A510b4] = 322; // seq: 322 -> tkn_id: 322 claimers[0xD40356b1304CD0c7Ae2a07ea45917552001b6ed9] = 323; // seq: 323 -> tkn_id: 323 claimers[0x4622fc2DaB3E3E4e1c2d67B8E1Ecf0c63b517d80] = 324; // seq: 324 -> tkn_id: 324 claimers[0xA63328aE7c2Da36133D1F2ecFB9074403667EfE4] = 325; // seq: 325 -> tkn_id: 325 claimers[0x86fce8cB12e663eD626b20E48F1e9095e930Bfa3] = 327; // seq: 326 -> tkn_id: 327 claimers[0xC28Ac85a4A2b5C7B99cA997B9c4919a7f300A2DA] = 328; // seq: 327 -> tkn_id: 328 claimers[0xCbc3906EFE25eD7CF06265f6B02e83dB67eF41AC] = 329; // seq: 328 -> tkn_id: 329 claimers[0xC64E4d5Ecda0b4D8d9255340c9E3B138c846F17F] = 330; // seq: 329 -> tkn_id: 330 claimers[0x3a434BBF72AF14Ae7cBf25c5cFA19Afe6A25510c] = 331; // seq: 330 -> tkn_id: 331 claimers[0xEC712Ce410df07c9a5a38954d1A85520410b8b83] = 332; // seq: 331 -> tkn_id: 332 claimers[0x640Ea12876aE881c578ab5C953F30e6cA2F6b51A] = 333; // seq: 332 -> tkn_id: 333 claimers[0x266EEC4B2968fd655C362B1D1c5a9269caD4aA42] = 334; // seq: 333 -> tkn_id: 334 claimers[0x79ff9938d22D39d6FA7E774637FA6D5cfc0897Cc] = 335; // seq: 334 -> tkn_id: 335 claimers[0xE513dE08500025E9a15E0cb54B232169e5c169BC] = 336; // seq: 335 -> tkn_id: 336 claimers[0xe7F032d734Dd90F2011E46170493f4Ad335C583f] = 337; // seq: 336 -> tkn_id: 337 claimers[0x20a6Dab0c262c28CD9ed6F96A08309220a60601A] = 338; // seq: 337 -> tkn_id: 338 claimers[0xB7da649e07D3C3406427124672bCf3318E4eAD88] = 339; // seq: 338 -> tkn_id: 339 claimers[0xA3D4f816c0deB4Da228D931D419cE2Deb7A362a8] = 340; // seq: 339 -> tkn_id: 340 claimers[0xDd0A2bE389cfc5f1Eb7BDa07147F3ddEa5692821] = 341; // seq: 340 -> tkn_id: 341 claimers[0x1C4Cdcd7f746Dd1d513fae4eBdC9abbca5068924] = 342; // seq: 341 -> tkn_id: 342 claimers[0xf13D7625bf1838c14Af331c5A5014Aea39CC9A8c] = 343; // seq: 342 -> tkn_id: 343 claimers[0xe2C05bB4ffAFfcc3d32039C9153b2bF8aa1C0613] = 344; // seq: 343 -> tkn_id: 344 claimers[0xB9e39A55b80f449cB847Aa679807b7e3309d22C3] = 345; // seq: 344 -> tkn_id: 345 claimers[0x2Bd69F9dFAf984aa97c2f443F4CAa4067B223f1A] = 346; // seq: 345 -> tkn_id: 346 claimers[0xeDf32B8F98D464b9Eb29C74202e6Baae28134fC7] = 347; // seq: 346 -> tkn_id: 347 claimers[0x59aD1737E02556E64487969c844646Dd3B451251] = 348; // seq: 347 -> tkn_id: 348 claimers[0x6895335Bbef92D7cE00465Ebe625fb84cc5fEc2F] = 349; // seq: 348 -> tkn_id: 349 claimers[0xbcBa4F18f391b9E7914E586a7477fbf56E42e90e] = 350; // seq: 349 -> tkn_id: 350 claimers[0x4fee40110623aD02BA4d76c76157D01e22DFbA72] = 351; // seq: 350 -> tkn_id: 351 claimers[0xa8f530a2F1cc7eCeba848BD089ffA923873a835e] = 352; // seq: 351 -> tkn_id: 352 claimers[0xC4b1bb0c1c8c29E234F1884b7787c7e14E1bC0a1] = 353; // seq: 352 -> tkn_id: 353 claimers[0xae3d939ffDc30837ba1b1fF24856e1249cDda61D] = 354; // seq: 353 -> tkn_id: 354 claimers[0x79d39642A48597A9943Cc64432bE1D50F25EFb2b] = 355; // seq: 354 -> tkn_id: 355 claimers[0x65772909024899817Fb7333EC50e4B05534e3dB1] = 356; // seq: 355 -> tkn_id: 356 claimers[0xce2C6c7c40bCe8718786484561a20fbE71416F9f] = 357; // seq: 356 -> tkn_id: 357 claimers[0x7777515751843e7cdcC47E10833E159c47777777] = 358; // seq: 357 -> tkn_id: 358 claimers[0x783a108e6bCD910d476aF96b5A49f54fE379C0eE] = 359; // seq: 358 -> tkn_id: 359 claimers[0xabF552b23902ccC9B1A36512cFaC9869a15C76F6] = 360; // seq: 359 -> tkn_id: 360 claimers[0x16c3576d3c85CBC564ac79bf5F48512ee42054f6] = 361; // seq: 360 -> tkn_id: 361 claimers[0x178025dc029CAA1ff1fEe4Bf4d2b60437ebE661c] = 362; // seq: 361 -> tkn_id: 362 claimers[0x68F38334ca94956AfC2DE794A1E8536eb055bECB] = 363; // seq: 362 -> tkn_id: 363 claimers[0x276A235D7822694C9738f441C777938eb6Dd2a7b] = 364; // seq: 363 -> tkn_id: 364 claimers[0xc7B5D7057BB3A77d8FFD89D3065Ad14E1E9deD7c] = 365; // seq: 364 -> tkn_id: 365 claimers[0xCf57A3b1C076838116731FDe404492D9d168747A] = 366; // seq: 365 -> tkn_id: 366 claimers[0x7eea2a6FEA12a60b67EFEAf4DbeCf028A2F41a2d] = 367; // seq: 366 -> tkn_id: 367 claimers[0xa72ce2426D395380756401fCA476cC6C3CF47354] = 368; // seq: 367 -> tkn_id: 368 claimers[0x5CaF975D380a6f8A4f25Dc9b5A1fC41eb714eF7C] = 369; // seq: 368 -> tkn_id: 369 claimers[0x764d8B7F4d75803008ACaec24745D978A7dF84D6] = 370; // seq: 369 -> tkn_id: 370 claimers[0x0BDfAA5444Eb0fd5E03bCB1ab34e10044971bF39] = 371; // seq: 370 -> tkn_id: 371 claimers[0x0DAddc0280b9B312c56d187BBBDDAFDcdB68Fe02] = 372; // seq: 371 -> tkn_id: 372 claimers[0x299B907233549Fa565d1C8D92429E2c6182F13B8] = 373; // seq: 372 -> tkn_id: 373 claimers[0xA30C27Bcc7A75045385941C7cF9415893ff45b1A] = 374; // seq: 373 -> tkn_id: 374 claimers[0x4E2ECa32c15389F8da0883d11E11d490A3e06d4D] = 375; // seq: 374 -> tkn_id: 375 claimers[0x9318Db19966B03fe3b2DC6A4A59d46d8C98f7c9f] = 376; // seq: 375 -> tkn_id: 376 claimers[0x524b7c9B4cA33ba72445DFd2d6404C81d8D1F2E3] = 377; // seq: 376 -> tkn_id: 377 claimers[0xB862D5e30DE97368801bDC24A53aD90F56a9C068] = 378; // seq: 377 -> tkn_id: 378 claimers[0x53C2A37BEef67489f0a19890F5fEb2Fc53384C72] = 379; // seq: 378 -> tkn_id: 379 claimers[0xe926545EA364a95473905e882f8559a091FD7383] = 380; // seq: 379 -> tkn_id: 380 claimers[0x73c18BEeF34332e91E94250781DcE0BA996c072b] = 381; // seq: 380 -> tkn_id: 381 claimers[0x5451C07DEb2bc853081716632c7827e84bd2e24A] = 382; // seq: 381 -> tkn_id: 382 claimers[0x47dab6E0FEA8f3664b201EBEA2700458C25C66cc] = 383; // seq: 382 -> tkn_id: 383 claimers[0x3dE345e0042cBBDa5e1080691d9439DC1A35933e] = 384; // seq: 383 -> tkn_id: 384 claimers[0xb8AB7c24f5C52Ed17f1f38Eb8286Bd1888D3D68e] = 385; // seq: 384 -> tkn_id: 385 claimers[0xd7201730Fd6d8769ca80c3a77905a397F8732e90] = 386; // seq: 385 -> tkn_id: 386 claimers[0x256b09f7Ae7d5fec8C8ac77184CA09F867BbBf4c] = 387; // seq: 386 -> tkn_id: 387 claimers[0xDaE5D2ceaC11c0a9F15f745e55744C108a5fb266] = 388; // seq: 387 -> tkn_id: 388 claimers[0x2A967A09304B8334BE70cF9D9E10469127E4303D] = 389; // seq: 388 -> tkn_id: 389 claimers[0xAA504202187c620EeB0B1434695b32a2eE24E043] = 390; // seq: 389 -> tkn_id: 390 claimers[0xA8231e126fB45EdFE070d72583774Ee3FE55EcD9] = 391; // seq: 390 -> tkn_id: 391 claimers[0x015b2738D14Da6d7775444E6Cf0b46E722F45aDD] = 392; // seq: 391 -> tkn_id: 392 claimers[0x56cbBaF7F1eB247c4F526fE3e2109f19e5f63994] = 393; // seq: 392 -> tkn_id: 393 claimers[0xA0f31bF73eD86ab881d6E8f5Ae2E4Ec9E81f04Fc] = 394; // seq: 393 -> tkn_id: 394 claimers[0x3A484fc4E7873Bd79D0B9B05ED6067A549eC9f49] = 395; // seq: 394 -> tkn_id: 395 claimers[0x184cfB6915daDb4536D397fEcfA4fD8A18823719] = 396; // seq: 395 -> tkn_id: 396 claimers[0xee86f2BAFC7e33EFDD5cf3970e33C361Cb7aDeD9] = 397; // seq: 396 -> tkn_id: 397 claimers[0x4D3c3E7F5EBae3aCBac78EfF2457a842Ab86577e] = 398; // seq: 397 -> tkn_id: 398 claimers[0xf459958a3e43A9d08e7ce4567cd6Bba37304642D] = 399; // seq: 398 -> tkn_id: 399 claimers[0xC1e4B49876c3D4b5F4DfbF635a31a7CAE738d8D4] = 400; // seq: 399 -> tkn_id: 400 claimers[0xc09e52C36BeFcF605a7f308824395753Bb5693CE] = 401; // seq: 400 -> tkn_id: 401 claimers[0xC383395EdCf07183c5190833859751836755E549] = 402; // seq: 401 -> tkn_id: 402 claimers[0x41D43f1fb956351F39925C17b6639DFe198c6E58] = 403; // seq: 402 -> tkn_id: 403 claimers[0xea52Fb67C64EE535e6493bDA464c1776B029E68a] = 404; // seq: 403 -> tkn_id: 404 claimers[0x769Fcbe8A35D6B2E30cbD16B32CA6BA7D124FA5c] = 405; // seq: 404 -> tkn_id: 405 claimers[0x2733Deb98cC52921701A1FA018Bc084E017D6C2B] = 406; // seq: 405 -> tkn_id: 406 claimers[0xFB81414570E338E28C98417c38A3A5c9C6503516] = 407; // seq: 406 -> tkn_id: 407 claimers[0x0bEb916792e88Bc018a60403c2A5B3E88bc94E8C] = 408; // seq: 407 -> tkn_id: 408 claimers[0xC9A9943A2230ae6b3423F00d1435f96950f82B23] = 409; // seq: 408 -> tkn_id: 409 claimers[0x65028EEE0F81E76A8Ffc39721eD4c18643cB9A4C] = 410; // seq: 409 -> tkn_id: 410 claimers[0x0e173d5df309000cA6bC3a48064b6dA90642C088] = 411; // seq: 410 -> tkn_id: 411 claimers[0x5dB10F169d7193cb5A9A1A787b06E973e0c670eA] = 412; // seq: 411 -> tkn_id: 412 claimers[0xa6eB69bCA906F5A463E4BEdaf98cFb6eF4AeAF5f] = 413; // seq: 412 -> tkn_id: 413 claimers[0x053AA35E51A8Ef8F43fd0d89dd24Ef40a8C91556] = 414; // seq: 413 -> tkn_id: 414 claimers[0x90DB49Ac2f9d9ae14E9adBB4666bBbc890495fb3] = 415; // seq: 414 -> tkn_id: 415 claimers[0xaF85Cf9A8a0AfAE6071aaBe8856f487C1790Ef32] = 416; // seq: 415 -> tkn_id: 416 claimers[0x1d69159798e83d8eB39842367869D52be5EeD87d] = 417; // seq: 416 -> tkn_id: 417 claimers[0xD0A5ce6b581AFF1813f4376eF50A155e952218D8] = 418; // seq: 417 -> tkn_id: 418 claimers[0x915af533bFC63D46ffD38A0589AF6d2f5AC86B23] = 419; // seq: 418 -> tkn_id: 419 claimers[0xe5abD6895aE353496E4b44E212085B91bCD3274A] = 420; // seq: 419 -> tkn_id: 420 claimers[0x14b0b438A346d8555148e3765Cc3E6FE911546D5] = 421; // seq: 420 -> tkn_id: 421 claimers[0xAa7708065610BeEFB8e1aead8E27510bf5d5C3A8] = 422; // seq: 421 -> tkn_id: 422 claimers[0x2800D157C4D77F234AC49f401076BBf79fef6fF3] = 423; // seq: 422 -> tkn_id: 423 claimers[0xF33782f1384a931A3e66650c3741FCC279a838fC] = 424; // seq: 423 -> tkn_id: 424 claimers[0x20B5db733532A6a36B41BFE62bD177B6FA9622e7] = 425; // seq: 424 -> tkn_id: 425 claimers[0xa086F516d4591c0D2c67d9ABcbfee0D598eB3988] = 426; // seq: 425 -> tkn_id: 426 claimers[0x572AD2e517CBC0E7EA60948DfF099Fafde9d8022] = 427; // seq: 426 -> tkn_id: 427 claimers[0xbE3164647cfF2518931454DD55FD2bA0C7B29297] = 428; // seq: 427 -> tkn_id: 428 claimers[0x239D5c0CfD4ED667ad78Cdc7F3DCB17D09740a0d] = 429; // seq: 428 -> tkn_id: 429 claimers[0xdAD3f7d6D9Fa998c804b0BD7Cc02FA0C243bEE17] = 430; // seq: 429 -> tkn_id: 430 claimers[0x96C7fcC0d3426714Bf62c4B508A0fBADb7A9B692] = 431; // seq: 430 -> tkn_id: 431 claimers[0x2c46bc2F0b73b75248567CA25db6CA83d56dEA65] = 432; // seq: 431 -> tkn_id: 432 claimers[0x2220d8b0539CB4613A5112856a9B192b380be37f] = 433; // seq: 432 -> tkn_id: 433 claimers[0xcC3ee4f6002B17E741f6d753Da3DBB0c0EFbbC0F] = 434; // seq: 433 -> tkn_id: 434 claimers[0x6E9B220B915b6E18A1C36B6B7bcc5bde9838142B] = 435; // seq: 434 -> tkn_id: 435 claimers[0x3d370054667010D228822b60eA8e92A6491c6f13] = 436; // seq: 435 -> tkn_id: 436 claimers[0xd63613F91a6EFF9f479e052dF2c610108FE48048] = 437; // seq: 436 -> tkn_id: 437 claimers[0x0be82Fe1422d6D5cA74fd73A37a6C89636235B25] = 438; // seq: 437 -> tkn_id: 438 claimers[0xfA79F7c2601a4C2A40C80eC10cE0667988B0FC36] = 439; // seq: 438 -> tkn_id: 439 claimers[0x3786F2693B144d14b205B7CD719c71A95ffB8F82] = 440; // seq: 439 -> tkn_id: 440 claimers[0x88D09b28739B6C301be94b76Aab0554bde287D50] = 441; // seq: 440 -> tkn_id: 441 claimers[0xbdB1aD55728Be046C4eb3C24406c60fA8EB40A4F] = 442; // seq: 441 -> tkn_id: 442 claimers[0xF77bC2475ad7D0830753C87C375Fe9dF443dD1f5] = 443; // seq: 442 -> tkn_id: 443 claimers[0x0667b277d3CC7F8e0dc0c2106bD546214dB7B4B7] = 444; // seq: 443 -> tkn_id: 444 claimers[0x87698583DB020081DA64713E7A75D6276F970Ea6] = 445; // seq: 444 -> tkn_id: 445 claimers[0x49CEC0c4ec7B40e10aD2c46E4c863Fff9f0F8D09] = 446; // seq: 445 -> tkn_id: 446 claimers[0xAfc6bcc856644AA00A2e076e2EdDbA607326c517] = 447; // seq: 446 -> tkn_id: 447 claimers[0x8D8d7315f31C04c96E5c3944eE332599C3533131] = 448; // seq: 447 -> tkn_id: 448 claimers[0xc65D945aaAB7D2928A0bd9a51602451BD24E17cb] = 449; // seq: 448 -> tkn_id: 449 claimers[0x3A79caC51e770a84E8Cb5155AAafAA9CaC83F429] = 450; // seq: 449 -> tkn_id: 450 claimers[0x2b2248E158Bfe5710b82404b6Af9ceD5aE90b859] = 451; // seq: 450 -> tkn_id: 451 claimers[0x9c3C4d995BF0Cea85edF50ec552D1eEb879e1a47] = 452; // seq: 451 -> tkn_id: 452 claimers[0x93C927A836bF0CD6f92760ECB05E46A67D8A3FB3] = 453; // seq: 452 -> tkn_id: 453 claimers[0xaa8404c21A938551aD09719392a0Ed282538305F] = 454; // seq: 453 -> tkn_id: 454 claimers[0x03bE7e943c99eaF1630033adf8A9B8DE68e25D6E] = 455; // seq: 454 -> tkn_id: 455 claimers[0x2a8D7c661828c4e312Cde8e2CD8Ab63a1aCAD396] = 456; // seq: 455 -> tkn_id: 456 claimers[0xBeB6Bdb317bf0D7a3b3dA1D39bD07313b35c983f] = 457; // seq: 456 -> tkn_id: 457 claimers[0xf1180102846D1b587cD326358Bc1D54fC7441ec3] = 458; // seq: 457 -> tkn_id: 458 claimers[0x931ddC55Ea7074a190ded7429E82dfAdFeDC0269] = 459; // seq: 458 -> tkn_id: 459 claimers[0x871cAEF9d39e05f76A3F6A3Bb7690168f0188925] = 460; // seq: 459 -> tkn_id: 460 claimers[0x131BA338c35b0954Fd483C527852828B378666Db] = 461; // seq: 460 -> tkn_id: 461 claimers[0xADeA561251c72328EDf558CB0eBE536ae864fD74] = 462; // seq: 461 -> tkn_id: 462 claimers[0xdCB7Bf063D73FA67c987f459D885b3Df86061548] = 463; // seq: 462 -> tkn_id: 463 claimers[0xDaac8766ef95E86D839768F7EFf7ed972CA30628] = 464; // seq: 463 -> tkn_id: 464 claimers[0x07F3813CB3A7302eF49903f112e9543D44170a50] = 465; // seq: 464 -> tkn_id: 465 claimers[0x55E9762e2aa135584969DCd6A7d550A0FaadBcd6] = 466; // seq: 465 -> tkn_id: 466 claimers[0xca0d901CF1dddf950431849B2F200524C12baC1D] = 467; // seq: 466 -> tkn_id: 467 claimers[0x315a99D2403C2bdb04265ce74Ca375b513C7f0a4] = 468; // seq: 467 -> tkn_id: 468 claimers[0x05BE7F4a524a7169F66348d3A71CFc49654961EB] = 469; // seq: 468 -> tkn_id: 469 claimers[0x8D88F01D183DDfD30782E565fdBcD85c14413cAF] = 470; // seq: 469 -> tkn_id: 470 claimers[0xFb4ad2136d64C83762D9AcbAb12837ed0d47c1D4] = 471; // seq: 470 -> tkn_id: 471 claimers[0xD3Edeb449B2F93210D19e19A9E7f348998F437EC] = 472; // seq: 471 -> tkn_id: 472 claimers[0x9a1094393c60476FF2875E581c07CDbb51B8d63e] = 473; // seq: 472 -> tkn_id: 473 claimers[0x4F14B92dB4021d1545d396ba529c02464C692044] = 474; // seq: 473 -> tkn_id: 474 claimers[0xbb8b593aE36FaDFE56c20A054Bc095DFCcd000Ec] = 475; // seq: 474 -> tkn_id: 475 claimers[0xC0FFd04728F3D0Dd3d355d1DdE4F65740565A640] = 476; // seq: 475 -> tkn_id: 476 claimers[0x236D33B5CdBC9b44Ab2C5B0D3B43B3C365f7f455] = 477; // seq: 476 -> tkn_id: 477 claimers[0x31981027E99D7322bbfAAdC056e26c908b1A4eAf] = 478; // seq: 477 -> tkn_id: 478 claimers[0xa7A2FeB7fe3414832fc8DC0f55dcd66F04536C56] = 479; // seq: 478 -> tkn_id: 479 claimers[0x68E9496F98652a2FcFcA5a81B44A03D177567844] = 480; // seq: 479 -> tkn_id: 480 claimers[0x21130c9b9D00BcB6cDAF24d0E85809cf96251F35] = 481; // seq: 480 -> tkn_id: 481 claimers[0x0Ab49FcBdcf3D8d369D0C9E7Cd620e668c98C296] = 482; // seq: 481 -> tkn_id: 482 claimers[0x811Fc30D7eD89438E2FFad5df1Bd8F7560F41a37] = 483; // seq: 482 -> tkn_id: 483 claimers[0xb62C16D2D70B0121697Ed4ca4D5BAbeb5d573f8e] = 484; // seq: 483 -> tkn_id: 484 claimers[0x5E0bD50345356FdD6f3bDB7398D80e027975Ddf3] = 485; // seq: 484 -> tkn_id: 485 claimers[0x0118838575Be097D0e41E666924cd5E267ceF444] = 486; // seq: 485 -> tkn_id: 486 claimers[0x044D9739cAC0eE9aCB33D83a949ec7A4Ba342de4] = 487; // seq: 486 -> tkn_id: 487 claimers[0x3d8D1C9A6Db0C49774f28fE2E81C0083032522Be] = 488; // seq: 487 -> tkn_id: 488 claimers[0xCB95dC3DF3007330A5C6Ea57a7fBD0024F3560C0] = 489; // seq: 488 -> tkn_id: 489 claimers[0xcafEfe36aDE7561bb28037Ac8807AA4a5b22102e] = 490; // seq: 489 -> tkn_id: 490 claimers[0x2230A3fa220B0234E468a52389272d239CEB809d] = 491; // seq: 490 -> tkn_id: 491 claimers[0xA504BcF03748740b49dDA8b26BF3081D9dcd3114] = 492; // seq: 491 -> tkn_id: 492 claimers[0x357494619Aa4419437D10970E9F953c26C1aF51d] = 493; // seq: 492 -> tkn_id: 493 claimers[0x57AAeAB03d27B0EF9Dd45c79F3dd486b912e4Ed9] = 494; // seq: 493 -> tkn_id: 494 claimers[0x0753B66aA5652bA60F1b33C34Ee1E9bD85E0dC88] = 495; // seq: 494 -> tkn_id: 495 claimers[0xbbd85FE0869340D1458d593fF8379aed857C00aC] = 496; // seq: 495 -> tkn_id: 496 claimers[0x84c51a0237Bda0b4b0F820e03DB70a035e26Dd15] = 497; // seq: 496 -> tkn_id: 497 claimers[0x22827dF138Fb40F2A80c00245aF2177b5eB71F38] = 498; // seq: 497 -> tkn_id: 498 claimers[0x0Acc621E4956d1102DE13F1D8ED9B80dC98b8F5f] = 499; // seq: 498 -> tkn_id: 499 claimers[0xff8994c6a99a44b708dEA64897De7E4DD0Fb3939] = 500; // seq: 499 -> tkn_id: 500 claimers[0x2a0948cfFe88e193F453084A8702b59D8FeC6D5a] = 501; // seq: 500 -> tkn_id: 501 claimers[0x5a90f33f31924f0b502602C7f6a00F43EAaB7C0A] = 502; // seq: 501 -> tkn_id: 502 claimers[0x66251D264ED22E4eD362EA0FBDc3D96028786e85] = 503; // seq: 502 -> tkn_id: 503 claimers[0x76B8AeCDaC440a1f3bf300DE29bd0A652B67a94F] = 504; // seq: 503 -> tkn_id: 504 claimers[0x0534Ce5CbB832140d3B6a372217eEA65c4d8A65c] = 505; // seq: 504 -> tkn_id: 505 claimers[0x59897640bBF64426747BDf14bA4B9509c7404f77] = 506; // seq: 505 -> tkn_id: 506 claimers[0x7ACB9314364c7Fe3b01bc6B41E95eF3D360456d9] = 507; // seq: 506 -> tkn_id: 507 claimers[0xd2f97ADbe4bF3eaB86cA464c8C652977Ec72E51f] = 508; // seq: 507 -> tkn_id: 508 claimers[0xEc8c50223E785C3Ff21fd9F9ABafAcfB1e2215FC] = 509; // seq: 508 -> tkn_id: 509 claimers[0x843E8e7996F10d397b7C8b6251A035518D10D437] = 510; // seq: 509 -> tkn_id: 510 claimers[0x190f7a8e33E07d1230FA8C42bea1392606D02808] = 511; // seq: 510 -> tkn_id: 511 claimers[0x5c33ed519972c7cD746D261dcbBDa8ee6F9aadA7] = 512; // seq: 511 -> tkn_id: 512 claimers[0x1A33aC98AB15Ed89147Fe0edd5B726565d7972c9] = 513; // seq: 512 -> tkn_id: 513 claimers[0x915855E0b041468A8497c2E1D0959780904dA171] = 514; // seq: 513 -> tkn_id: 514 claimers[0x2Ee0781c7CE1f1BDe71fD2010F06448420873e58] = 515; // seq: 514 -> tkn_id: 515 claimers[0xC8ab8461129fEaE84c4aB3929948235106514AdF] = 516; // seq: 515 -> tkn_id: 516 claimers[0x75daA09CE22eD9e4e27cB1f2D0251647831642A6] = 517; // seq: 516 -> tkn_id: 517 claimers[0xA31D7fe5acCBBA9795b4B2f8c1b58abE90590D6d] = 518; // seq: 517 -> tkn_id: 518 claimers[0x85d03E980A35517906a3665866E8a255C0212918] = 519; // seq: 518 -> tkn_id: 519 claimers[0x02A325603C41c24E1897C74840B5C78950223366] = 520; // seq: 519 -> tkn_id: 520 claimers[0xF2CA16da81687313AE2d8d3DD122ABEF11e1f68f] = 521; // seq: 520 -> tkn_id: 521 claimers[0xba028A2a6097f7Da63866965B7f045F166aeB958] = 522; // seq: 521 -> tkn_id: 522 claimers[0x787Efe41F4C940bC8c2a0D2B1877B7Fb71bC7c04] = 523; // seq: 522 -> tkn_id: 523 claimers[0xA368bae3df1107cF22Daf0a79761EF94656D789A] = 524; // seq: 523 -> tkn_id: 524 claimers[0x67ffa298DD79AE9de27Fd63e99c15716ddc93491] = 525; // seq: 524 -> tkn_id: 525 claimers[0xD79B70C1D4Ab78Cd97d53508b5CBf0D573728980] = 526; // seq: 525 -> tkn_id: 526 claimers[0x8aA79517903E473c548A36d80f54b7669056249a] = 527; // seq: 526 -> tkn_id: 527 claimers[0xaEC4a7621BEA9F03B9A893d61e6e6EA91b33c395] = 528; // seq: 527 -> tkn_id: 528 claimers[0xF6614172a85D7cB91327bd11e4884d3C76042580] = 529; // seq: 528 -> tkn_id: 529 claimers[0x8F1B34eAF577413db89889beecdb61f4cc590aC2] = 530; // seq: 529 -> tkn_id: 530 claimers[0xD85bc15495DEa1C510fE41794d0ca7818d8558f0] = 531; // seq: 530 -> tkn_id: 531 claimers[0x85b931A32a0725Be14285B66f1a22178c672d69B] = 532; // seq: 531 -> tkn_id: 532 claimers[0xCDCaDF2195c1376f59808028eA21630B361Ba9b8] = 533; // seq: 532 -> tkn_id: 533 claimers[0x32527CA6ec2B85AbaCA0fb2dd3878e5b7Bb5b370] = 534; // seq: 533 -> tkn_id: 534 claimers[0xe3fa3aefD1f122e2228fFE79EE36685215A05BCa] = 535; // seq: 534 -> tkn_id: 535 claimers[0x7AE29F334D7cb67b58df5aE2A19F360F1Fd3bE75] = 536; // seq: 535 -> tkn_id: 536 claimers[0xF29919b09037036b6f10aD7C41ADCE8677BE2F54] = 537; // seq: 536 -> tkn_id: 537 claimers[0x328824B1468f47163787d0Fa40c44a04aaaF4fD9] = 538; // seq: 537 -> tkn_id: 538 claimers[0x4d4180739775105c82627CCbf043d6d32e746dee] = 539; // seq: 538 -> tkn_id: 539 claimers[0x6372b52593537A3Be2F3752110cb709e6f213241] = 540; // seq: 539 -> tkn_id: 540 claimers[0x75187bA60caFC4A2Cb057aADdD5c9FdAc3896Cee] = 541; // seq: 540 -> tkn_id: 541 claimers[0xf5503988423F65b1d5F2263d33Ab161E889103EB] = 542; // seq: 541 -> tkn_id: 542 claimers[0x76b2e65407e9f24cE944B62DB0c82e4b61850233] = 543; // seq: 542 -> tkn_id: 543 claimers[0xDd6177ba0f8C5F15DB178452585BB52A7b0C9Aee] = 544; // seq: 543 -> tkn_id: 544 claimers[0x3017dC24849823c81c43b6F8288bC85D6214FD7E] = 545; // seq: 544 -> tkn_id: 545 claimers[0xdf59a1d81880bDE9175c3B766c3e95bEd21c3670] = 546; // seq: 545 -> tkn_id: 546 claimers[0x2A716b58127BC4341231833E3A586582b07bBB22] = 547; // seq: 546 -> tkn_id: 547 claimers[0x15c5F3a14d4492b1a26f4c6557251a6F247a2Dd5] = 548; // seq: 547 -> tkn_id: 548 claimers[0x239af5a76A69de3F13aed6970fdF37bf86e8FEB7] = 549; // seq: 548 -> tkn_id: 549 claimers[0xCF6E7e0676f5AC61446F6865e26a0f34bb86A622] = 550; // seq: 549 -> tkn_id: 550 claimers[0xfb580744F1fDc4fEb83D9846E907a63Aa94979bd] = 551; // seq: 550 -> tkn_id: 551 claimers[0x3de1820D8d3B7f6C61C34dfD74F941c88cb27143] = 552; // seq: 551 -> tkn_id: 552 claimers[0xDFfF9Df5665BD156ECc71769103C72D8D167E30b] = 553; // seq: 552 -> tkn_id: 553 claimers[0xf4775496624C382f74aDbAE79C5780F353B1f83B] = 554; // seq: 553 -> tkn_id: 554 claimers[0xd1f157e1798D20F905e8391e3AcC2351bd9873Ff] = 555; // seq: 554 -> tkn_id: 555 claimers[0x2BcfEC37A16eb258d641812A308edEc5B80b32C1] = 556; // seq: 555 -> tkn_id: 556 claimers[0xD7CE5Cec413cC35edc293BD0e9D6204bEb91a470] = 557; // seq: 556 -> tkn_id: 557 claimers[0xC195a064BE7Ac37702Cd8FBcE4d71b57111d559b] = 558; // seq: 557 -> tkn_id: 558 claimers[0xc148113F6508589538d65B29426331A12B04bC6C] = 559; // seq: 558 -> tkn_id: 559 claimers[0x687922176D1BbcBcdC295E121BcCaA45A1f40fCd] = 560; // seq: 559 -> tkn_id: 560 claimers[0xba5270bFd7245C37db5e9Bb5fC18A68b8cA622F8] = 561; // seq: 560 -> tkn_id: 561 claimers[0x2022e7E902DdF290B70AAF5FB5D777E7840Fc9D3] = 562; // seq: 561 -> tkn_id: 562 claimers[0x676be4D726F6e648cC41AcF71b3d099dC65242f3] = 563; // seq: 562 -> tkn_id: 563 claimers[0xCbBdE3eeb1005A8be374C0eeB9c02e0e33Ac4629] = 564; // seq: 563 -> tkn_id: 564 claimers[0xaf636e6585a1cD5CDD23A75d32cbd57e6D836dA6] = 565; // seq: 564 -> tkn_id: 565 claimers[0x7dE08dAb472F16F6713bD30B1B1BCd29FA7AC68c] = 566; // seq: 565 -> tkn_id: 566 claimers[0xc8fa8A80D241a06CB53d61Ceacce0d1a8715Bc2f] = 567; // seq: 566 -> tkn_id: 567 claimers[0xA661Ff505C9Be09C08341666bbB32c46a80Fe996] = 568; // seq: 567 -> tkn_id: 568 claimers[0x934Cc457EDC4b58b105188C3ECE78c7b2EE65d80] = 569; // seq: 568 -> tkn_id: 569 claimers[0xFF4a498B23f2E3aD0A5eBEd838F07F30Ab4dC800] = 570; // seq: 569 -> tkn_id: 570 claimers[0xf75b052036dB7d90D18C10C06d3535F0fc3A4b74] = 571; // seq: 570 -> tkn_id: 571 claimers[0x8f2a707153378551c450Ec28B29c72C0B97664FC] = 572; // seq: 571 -> tkn_id: 572 claimers[0x77167885E8393f1052A8cE8D5dfF2fF16c08f98d] = 573; // seq: 572 -> tkn_id: 573 claimers[0x186D482EB263492318Cd470f3e4C0cf7705b3963] = 574; // seq: 573 -> tkn_id: 574 claimers[0x0736C28bd6186Cc899F72aB3f68f542bC2479d90] = 575; // seq: 574 -> tkn_id: 575 claimers[0x5E6DbCb38555ec7B4c5C12F19144736010335d26] = 576; // seq: 575 -> tkn_id: 576 claimers[0xd85d3AcC28A235f9128938B99E26747dB0ba655D] = 577; // seq: 576 -> tkn_id: 577 claimers[0x812E1eeE6D76e2F3490a8C29C0CC9e38D71a1a4f] = 578; // seq: 577 -> tkn_id: 578 claimers[0x66D61B6BEb130197E8194B072215d9aE9b36e14d] = 579; // seq: 578 -> tkn_id: 579 claimers[0x36986961cc3037E40Ef6f01A7481941ed08aF566] = 580; // seq: 579 -> tkn_id: 580 claimers[0xB6ea652fBE96DeddC5fc7133C208D024f3CFFf5a] = 581; // seq: 580 -> tkn_id: 581 claimers[0x2F86c6e97C4E2d03939AfE7452448bD96b681938] = 582; // seq: 581 -> tkn_id: 582 claimers[0x6F36a7E4eA93aCbF753397C96DaBacD45ba88175] = 583; // seq: 582 -> tkn_id: 583 claimers[0x6394e38E5Fe6Fb9de9B2dD267F257035fe72a315] = 584; // seq: 583 -> tkn_id: 584 claimers[0xeE74a1e81B6C55e3D02D05D7CaE9FD6BCee0E651] = 585; // seq: 584 -> tkn_id: 585 claimers[0x9A7797Cf292579065CC204C5c975E0E7E9dF66f7] = 586; // seq: 585 -> tkn_id: 586 claimers[0xf50E61952aC37fa5DD770657326A5FBDB18cB694] = 587; // seq: 586 -> tkn_id: 587 claimers[0x0B60fF27655bCd5E9444c5D1865ec8CD3B403146] = 588; // seq: 587 -> tkn_id: 588 claimers[0x35f382D9daA602A23AD988D5bf837B8e6A01d002] = 589; // seq: 588 -> tkn_id: 589 claimers[0xFF7C32e9D881e6cabBCE7C0C17564F54260C3872] = 590; // seq: 589 -> tkn_id: 590 claimers[0xdE437ad59B5fcad477eB90a4742916FD04c0193e] = 591; // seq: 590 -> tkn_id: 591 claimers[0xB9f2946b6f35d8BB4a1522e7628F24416947ddda] = 592; // seq: 591 -> tkn_id: 592 claimers[0x67AE8A6e6587e6219141dC5a5BE35f30Beb30C50] = 593; // seq: 592 -> tkn_id: 593 claimers[0x04b5b1906745FE9E501C10B3191118FA76CD76Ba] = 594; // seq: 593 -> tkn_id: 594 claimers[0xc793B339FC99A912d8c4c420f55023e072Dc4A08] = 595; // seq: 594 -> tkn_id: 595 claimers[0x024713784f675dd28b5CE07dB91a4d47213c2394] = 596; // seq: 595 -> tkn_id: 596 claimers[0xE9011643a76aC1Ee4BDb32242B28424597C724A2] = 597; // seq: 596 -> tkn_id: 597 claimers[0xFA3ed3EDd606157c2FD49c900a0B1fE867b96d78] = 598; // seq: 597 -> tkn_id: 598 claimers[0xEb06301D471b0F8C8C5CC965B09Ce0B85021D398] = 599; // seq: 598 -> tkn_id: 599 claimers[0x57985E22ae7906cC693b44cC16473643F294Ff07] = 600; // seq: 599 -> tkn_id: 600 claimers[0x3ef7Bf350074EFDE3FD107ce38e652a10a5750f5] = 601; // seq: 600 -> tkn_id: 601 claimers[0xAA5990c918b845EE54ade1a962aDb9ddfF17D20A] = 602; // seq: 601 -> tkn_id: 602 claimers[0x7Ff698e124d1D14E6d836aF4dA0Ae448c8FfFa6F] = 603; // seq: 602 -> tkn_id: 603 claimers[0x95351210cf4F6270aaD413d5A2E07256a005D9B3] = 604; // seq: 603 -> tkn_id: 604 claimers[0x2aE024C5EE8dA720b9A51F50D53a291aca37dEb1] = 605; // seq: 604 -> tkn_id: 605 claimers[0xe0dAA80c1fF85fd070b561ef44cC7637059E5e57] = 606; // seq: 605 -> tkn_id: 606 claimers[0xD64212269c456D61bCA45403c4B93A2a57B7510E] = 607; // seq: 606 -> tkn_id: 607 claimers[0xC3A9eB254C875750A83750d1258220fA8a729F89] = 608; // seq: 607 -> tkn_id: 608 claimers[0x07b678695690183C644fEb37d9E95eBa4eFe53A8] = 609; // seq: 608 -> tkn_id: 609 claimers[0x4334c48D71b8D03799487a601509ac137b29904B] = 610; // seq: 609 -> tkn_id: 610 claimers[0xea2D190cBb3Be5074E9E144EDE095f059eDB7E53] = 611; // seq: 610 -> tkn_id: 611 claimers[0x93973b0dc20bEff165C087cB2A319640C210f30e] = 612; // seq: 611 -> tkn_id: 612 claimers[0x8015eA3DA10b9960378CdF6d529EBf19553c112A] = 613; // seq: 612 -> tkn_id: 613 claimers[0xE40Cc4De1a57e83AAc249Bb4EF833B766f26e2F2] = 614; // seq: 613 -> tkn_id: 614 claimers[0xdD2B93A4F52C138194C10686f175df55db690117] = 615; // seq: 614 -> tkn_id: 615 claimers[0x2EF48fA1785aE0C24fd791c1D7BAaf690d153793] = 616; // seq: 615 -> tkn_id: 616 claimers[0x2044E9cF4a61D4a49C73800168Ecfd8Bd19550c4] = 617; // seq: 616 -> tkn_id: 617 claimers[0xF6711aFF1462fd2f477769C2d442Cf2b10597C6D] = 618; // seq: 617 -> tkn_id: 618 claimers[0xf9F49E8B93f60535852A91FeE294fF6c4D460035] = 619; // seq: 618 -> tkn_id: 619 claimers[0x61b3c4c9dc16B686eD396319D48586f40c1F74E9] = 620; // seq: 619 -> tkn_id: 620 claimers[0x348F0cE2c24f14EfC18bfc2B2048726BDCDB759e] = 621; // seq: 620 -> tkn_id: 621 claimers[0x32f8E5d3F4039d1DF89B6A1e544288289A500Fd1] = 622; // seq: 621 -> tkn_id: 622 claimers[0xaF997affb94c5Ca556b28b024E162AA3164f4A43] = 623; // seq: 622 -> tkn_id: 623 claimers[0xb20Ce1911054DE1D77E1a66ec402fcB3d06c06c2] = 624; // seq: 623 -> tkn_id: 624 claimers[0xB83FC0c399e46b69e330f19baEB87B6832Ec890d] = 625; // seq: 624 -> tkn_id: 625 claimers[0x01B9b335Bb0D8Ff543f54eb9A59Ba57dBEf7A93B] = 626; // seq: 625 -> tkn_id: 626 claimers[0x2CC7dA5EF8fd01f4a7cD03E785A01941F28fE8da] = 627; // seq: 626 -> tkn_id: 627 claimers[0x46f75A3e9702d89E3E269361D9c1e4D2A9779044] = 628; // seq: 627 -> tkn_id: 628 claimers[0x7AEBDD84821190c1cfCaCe051E87913ae5d67439] = 629; // seq: 628 -> tkn_id: 629 claimers[0xE94F4519Ed1670123714d8f67B3A144Bf089f594] = 630; // seq: 629 -> tkn_id: 630 claimers[0xf10367decc6F0e6A12Aa14E7512AF94a4C791Fd7] = 631; // seq: 630 -> tkn_id: 631 claimers[0x49BA4256FE65b833b3dA9c26aA27E1eFD74EFD1d] = 632; // seq: 631 -> tkn_id: 632 claimers[0x33BE249B512DCb6D2FC7586047ab0220397aF2d3] = 633; // seq: 632 -> tkn_id: 633 claimers[0x07b449319D200b1189406c58967348c5bA0D4083] = 634; // seq: 633 -> tkn_id: 634 claimers[0x9B6498Ef7F47223f5F7d466FC4D26c570C7b375F] = 635; // seq: 634 -> tkn_id: 635 claimers[0xA40F625ce8e06Db1C41Bb7F8854C7d57644Ff9Cc] = 636; // seq: 635 -> tkn_id: 636 claimers[0x28864AF76e73B38e2C9D4e856Ea97F66947961aB] = 637; // seq: 636 -> tkn_id: 637 claimers[0x4aC4Ab29F4A87150D89D3fdd5cbC46112606E5e8] = 638; // seq: 637 -> tkn_id: 638 claimers[0x9D29BBF508cDf300D116FCA3cE3cd9d287850ccd] = 639; // seq: 638 -> tkn_id: 639 claimers[0xcC5Fb93A6e274Ac3C626a02B24F939b1307b46e1] = 640; // seq: 639 -> tkn_id: 640 claimers[0x0E590293aD7CB2Dd9968B7f16eac9614451A63E1] = 641; // seq: 640 -> tkn_id: 641 claimers[0x726d54570632b30c957E60CFf44AD4eE2b559dB6] = 642; // seq: 641 -> tkn_id: 642 claimers[0xE2927F7f6618E71A86CE3F8F5AC32B5BbFe163a6] = 643; // seq: 642 -> tkn_id: 643 claimers[0x3C7DEd16d0E5b5bA9fb3DE539ed28cb7B7D8C95C] = 644; // seq: 643 -> tkn_id: 644 claimers[0xB7c3A0928c06A80DC4A4CDc9dC0aec33E047A4c8] = 645; // seq: 644 -> tkn_id: 645 claimers[0x95f26898b144FF93283d38d0B1A92b69f90d3123] = 646; // seq: 645 -> tkn_id: 646 claimers[0x95a788A34b7781eF34660196BB615A97F7e7d2B8] = 647; // seq: 646 -> tkn_id: 647 claimers[0x317EA9Dd8fCac5A6Fd94eB2959FeC690931b61b8] = 648; // seq: 647 -> tkn_id: 648 claimers[0x2CE83785eD44961959bf5251e85af897Ba9ddAC7] = 649; // seq: 648 -> tkn_id: 649 claimers[0xE144E7e3948dCA4AD395794031A0289a83b150A0] = 650; // seq: 649 -> tkn_id: 650 claimers[0x18668B0244949570ec637465BAFdDe4d082afa69] = 651; // seq: 650 -> tkn_id: 651 claimers[0xaba035729057984c7431a711436D3e51e947cbD4] = 652; // seq: 651 -> tkn_id: 652 claimers[0x2519410f255A52CDF22a7DFA870073b1357B30A7] = 653; // seq: 652 -> tkn_id: 653 claimers[0x63a12D51Ee95eF213404308e1F8a2805A0c21899] = 654; // seq: 653 -> tkn_id: 654 claimers[0x882bBB07991c5c2f65988fd077CdDF405FE5b56f] = 655; // seq: 654 -> tkn_id: 655 claimers[0x11f53fdAb3054a5cA63778659263aF0838b642b1] = 656; // seq: 655 -> tkn_id: 656 claimers[0x093E088901909dEecC1b4a1479fBcCE1FBEd31E7] = 657; // seq: 656 -> tkn_id: 657 claimers[0x3c5cBddC5D6D6720d51CB563134d72E20dc4C713] = 658; // seq: 657 -> tkn_id: 658 claimers[0x3Db111A09A2e77A8DD6d03dc3f089f4A0F4557E9] = 659; // seq: 658 -> tkn_id: 659 claimers[0x8F53cA524c1451A930DEA18926df964Fb72B10F1] = 660; // seq: 659 -> tkn_id: 660 claimers[0x22C535D5EccCF398997eabA19Aa3FAbd3fe6AA16] = 661; // seq: 660 -> tkn_id: 661 claimers[0x93dF35071B3bc1B6d16D5f5F20fbB2be9D50FE67] = 662; // seq: 661 -> tkn_id: 662 claimers[0xfE61D830b99E40b3E905CD7EcF4a08DD06fa7F03] = 663; // seq: 662 -> tkn_id: 663 claimers[0x9cB5FAF0801ac959a0d40b2A7D69Ed8E42F792eA] = 664; // seq: 663 -> tkn_id: 664 claimers[0xC5B0f2afEC01807D964D76aEce6dB2F093239619] = 665; // seq: 664 -> tkn_id: 665 claimers[0x9b279dbaB2aE483EEDD106a583ACbBCFd722CE79] = 666; // seq: 665 -> tkn_id: 666 claimers[0x429c74f7C7fe7d31a70289e9B4b54e0F7300f376] = 667; // seq: 666 -> tkn_id: 667 claimers[0xeD08e8D72D35428b28390B7334ebe7F9f7a64822] = 668; // seq: 667 -> tkn_id: 668 claimers[0xB468076716C800Ce1eB9e9F515488099cC838128] = 669; // seq: 668 -> tkn_id: 669 claimers[0x3D7A35c89f04Af71F453b33848B49714859D061c] = 670; // seq: 669 -> tkn_id: 670 claimers[0x7DcE9e613b3583C600255A230497DD77429b0e21] = 671; // seq: 670 -> tkn_id: 671 claimers[0x2B00CaD253E88924290fFC7FeE221D135A0f083a] = 672; // seq: 671 -> tkn_id: 672 claimers[0xA2A64dE6BEe8c68DBCC948609708Ae54801CBAd8] = 673; // seq: 672 -> tkn_id: 673 claimers[0x6F255406306D6D78e97a29F7f249f6d2d85d9801] = 674; // seq: 673 -> tkn_id: 674 claimers[0xcDaf4c2e205A8077F29BF1dfF9Bd0B6a501B72cB] = 675; // seq: 674 -> tkn_id: 675 claimers[0xC45bF67A729B9A2b98521CDbCbf8bc70d8b81af3] = 676; // seq: 675 -> tkn_id: 676 claimers[0x35205135F0883e6a59aF9cb64310c53003433122] = 677; // seq: 676 -> tkn_id: 677 claimers[0xbAFcFC93A2fb6a042CA87f3d70670E2c114CE9fd] = 678; // seq: 677 -> tkn_id: 678 claimers[0xf664D1363FcE2da5ebb9aA935ef11Ce07be012Db] = 679; // seq: 678 -> tkn_id: 679 claimers[0x57e7ce99461FDeA80Ae8a6292e58AEfe053ed3a3] = 680; // seq: 679 -> tkn_id: 680 claimers[0xbD0Ad704f38AfebbCb4BA891389938D4177A8A92] = 681; // seq: 680 -> tkn_id: 681 claimers[0x0962FEeC7d4f0fa0EBadf6cd2e1CB783103B41F4] = 682; // seq: 681 -> tkn_id: 682 claimers[0x9B89f9Fd0952009fd556b19B18d85dA1089D005C] = 683; // seq: 682 -> tkn_id: 683 claimers[0xa511CB01cCe9c221cC73a9f9231937Cf6baf1D1A] = 684; // seq: 683 -> tkn_id: 684 claimers[0x79e5c907b9d4Af5840C687e6975a1C530895454a] = 685; // seq: 684 -> tkn_id: 685 claimers[0xf782f0Bf9B741FdE0E7c7dA4f71c7E33554f8397] = 686; // seq: 685 -> tkn_id: 686 claimers[0x228Bb6C83e8d0767eD342dd333DDbD55Ad217a3D] = 687; // seq: 686 -> tkn_id: 687 claimers[0xf2f62B5C7B3395b0ACe219d1B91D8083f8394720] = 688; // seq: 687 -> tkn_id: 688 claimers[0x2A77484F4cca78a5B3f71c22A50e3A1b8583072D] = 689; // seq: 688 -> tkn_id: 689 claimers[0xbB85877c4AEa11A141FC107Dc8D2E43C4B04F8C8] = 690; // seq: 689 -> tkn_id: 690 claimers[0x0414B2A60f8d4b84dE036677f8780F59AFEc1b65] = 691; // seq: 690 -> tkn_id: 691 claimers[0xb3aA296e046E0EFBd734cfa5DCd447Ae3a5e6104] = 692; // seq: 691 -> tkn_id: 692 claimers[0xa6700EA3f19830e2e8b35363c2978cb9D5630303] = 693; // seq: 692 -> tkn_id: 693 claimers[0xF976106afd7ADE91F8dFc5167284AD57795b17B1] = 694; // seq: 693 -> tkn_id: 694 claimers[0x793E446AFFf802e20bdb496A64250622BE32Df29] = 695; // seq: 694 -> tkn_id: 695 claimers[0x2E72d671fa07be54ae9671f793895520268eF00E] = 696; // seq: 695 -> tkn_id: 696 claimers[0xB67c99dfb3422b61f9E38070f021eaB7B42e9CAF] = 697; // seq: 696 -> tkn_id: 697 claimers[0x0095D1f7804D32A7921b26D3Eb1229873D3B11E0] = 698; // seq: 697 -> tkn_id: 698 claimers[0xEf31D013E222AaD9Eb90df9fd466c758B7603FaB] = 699; // seq: 698 -> tkn_id: 699 claimers[0x9936f05D5cE4259D44Aa51d54c0C245652efcc11] = 700; // seq: 699 -> tkn_id: 700 claimers[0x58bb897f0612235FA7Ae324F9b9718a06A2f6df3] = 701; // seq: 700 -> tkn_id: 701 claimers[0xa2cF94Bf60B6a6C08488B756E6695d990574e9C7] = 702; // seq: 701 -> tkn_id: 702 claimers[0x47754f6dCb011A308c91a666c5245abbC577c9eD] = 703; // seq: 702 -> tkn_id: 703 claimers[0xB6a95916221Abef28339594161cd154Bc650c515] = 704; // seq: 703 -> tkn_id: 704 claimers[0xb0471Ad0fEFD2151Efaa6C8415b1dB984526c0a6] = 705; // seq: 704 -> tkn_id: 705 claimers[0xC869ce145a5a72985540285Efde28f5176F39bC9] = 706; // seq: 705 -> tkn_id: 706 claimers[0x79440849d5BA6Df5fb1F45Ff36BE3979F4271fa4] = 707; // seq: 706 -> tkn_id: 707 claimers[0xD54F610d744b64393386a354cf1ADD944cBD42c9] = 708; // seq: 707 -> tkn_id: 708 claimers[0x3b368E77F110e3FE1C8482F395E51D1f75e50e5f] = 709; // seq: 708 -> tkn_id: 709 claimers[0x529ccAFA5aC0d18E7402244859AF8664BA736919] = 710; // seq: 709 -> tkn_id: 710 claimers[0x686241b898D7616FF78e22cc45fb07e92A74B7B5] = 711; // seq: 710 -> tkn_id: 711 claimers[0xd859ad8D8DCA1eEC61529833685FE59FAb804E7d] = 712; // seq: 711 -> tkn_id: 712 claimers[0x5AbfC4E2bB4941BD6773f120573618Ba8a4f7863] = 713; // seq: 712 -> tkn_id: 713 claimers[0x17c1cF2eeFda3f339996c67cd18d4389D132D033] = 714; // seq: 713 -> tkn_id: 714 claimers[0x6Ce5B05f0C6A8129DE3C7fC3E69ca35Be3ECB35e] = 715; // seq: 714 -> tkn_id: 715 claimers[0x4B992870CF27A548921082be7B447fc3c0534509] = 716; // seq: 715 -> tkn_id: 716 claimers[0xa278039DEE9B1fC58164Ef7B6f5eC86de9786178] = 717; // seq: 716 -> tkn_id: 717 claimers[0xBa64c61B45340994bABF676544025BcCc0bE6A9e] = 718; // seq: 717 -> tkn_id: 718 claimers[0x3656f4d852f15986beBE025AEF64a40dF2A5d4a1] = 719; // seq: 718 -> tkn_id: 719 claimers[0x4A57385D14882d6d8FDB3916792E9585102d22DA] = 720; // seq: 719 -> tkn_id: 720 claimers[0x764108BAcf10e30F6f249d17E7612fB9008923F0] = 721; // seq: 720 -> tkn_id: 721 claimers[0x880BD9ec1d3b71Bda5249baCCC63E9a8e5902250] = 722; // seq: 721 -> tkn_id: 722 claimers[0x1195e87Ca87C8f5989ecBa2d569E64784E5820f9] = 723; // seq: 722 -> tkn_id: 723 claimers[0x8591D21143794463A69017944F555E272965db06] = 724; // seq: 723 -> tkn_id: 724 claimers[0x032c255E5a84C2E8Ca242f85098988D69b982E85] = 725; // seq: 724 -> tkn_id: 725 claimers[0xFD9bCD1F71Cb016079077F659Ee99f8AD834732A] = 726; // seq: 725 -> tkn_id: 726 claimers[0x6Be049Bb4688dFf540E7798433c925E21c70Ac25] = 727; // seq: 726 -> tkn_id: 727 claimers[0xFbFB1aD08f5d60d0243CC88E1EDf9eD5875d2EFe] = 728; // seq: 727 -> tkn_id: 728 claimers[0xeBe91f187bF0b29185a8e4A362392Aa3665030a1] = 729; // seq: 728 -> tkn_id: 729 claimers[0xF6666FCE84FDe632f33c1A881b6AC2C0f545D271] = 730; // seq: 729 -> tkn_id: 730
seq: 56 -> tkn_id: 56
claimers[0x42de824dA4C1Af884ebEdaA2352Fd4d4e00445DF] = 56;
12,654,552
[ 1, 5436, 30, 13850, 317, 13030, 82, 67, 350, 30, 13850, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 14784, 414, 63, 20, 92, 9452, 323, 28, 3247, 72, 37, 24, 39, 21, 12664, 28, 5193, 24008, 41, 2414, 37, 4366, 9401, 27263, 24, 72, 24, 73, 713, 6334, 25, 4577, 65, 273, 13850, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x2964aE2d44937093B7D35B6B8d4cC5BfAE34B186/sources/project_/contracts/fNFT.sol
Set Valuation Data against provided tokenId.
function setValuationData( uint256 _tokenId, string memory _valuationsData, string memory _valuationFirm, string memory _timestamp, bool _updateJewellery, string memory _nFTTokenAddress ) public onlyOwner { Valuations memory valuations; valuations.valutionData = _valuationsData; valuations.valuationFirm = _valuationFirm; valuations.timestamp = _timestamp; valuations.updateJewellery = _updateJewellery; valuations.nFT_TokenAddress = _nFTTokenAddress; ValuationsData[_tokenId] = valuations; }
5,629,251
[ 1, 694, 776, 700, 367, 1910, 5314, 2112, 1147, 548, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 58, 700, 367, 751, 12, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 7010, 3639, 533, 3778, 389, 4531, 1012, 751, 16, 203, 3639, 533, 3778, 389, 4531, 367, 42, 3985, 16, 203, 3639, 533, 3778, 389, 5508, 16, 203, 3639, 1426, 389, 2725, 46, 359, 1165, 627, 16, 203, 3639, 533, 3778, 389, 82, 4464, 1345, 1887, 203, 3639, 262, 1071, 203, 565, 1338, 5541, 203, 565, 288, 203, 3639, 776, 700, 1012, 3778, 21748, 1012, 31, 203, 3639, 21748, 1012, 18, 1125, 1421, 751, 273, 389, 4531, 1012, 751, 31, 203, 3639, 21748, 1012, 18, 4531, 367, 42, 3985, 273, 389, 4531, 367, 42, 3985, 31, 203, 3639, 21748, 1012, 18, 5508, 273, 389, 5508, 31, 203, 3639, 21748, 1012, 18, 2725, 46, 359, 1165, 627, 273, 389, 2725, 46, 359, 1165, 627, 31, 203, 3639, 21748, 1012, 18, 82, 4464, 67, 1345, 1887, 273, 389, 82, 4464, 1345, 1887, 31, 203, 3639, 776, 700, 1012, 751, 63, 67, 2316, 548, 65, 273, 21748, 1012, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x0b6659a1a55c5038e34e8b0eeb9630c787466858 //Contract name: PentacoreCrowdsale //Balance: 0 Ether //Verification Date: 4/26/2018 //Transacion Count: 13 // CODE STARTS HERE pragma solidity ^0.4.21; // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/PentacoreToken.sol /** * @title Smart Contract which defines the token managed by the Pentacore Hedge Fund. * @author Jordan Stojanovski */ contract PentacoreToken is StandardToken { using SafeMath for uint256; string public name = 'PentacoreToken'; string public symbol = 'PENT'; uint256 public constant million = 1000000; uint256 public constant tokenCap = 1000 * million; // one billion tokens bool public isPaused = true; // Unlike the common practice to put the whitelist checks in the crowdsale, // the PentacoreToken does these tests itself. This is mandated by legal // issues, as follows: // - The exchange can be anywhere and it should not be concerned with // Pentacore's whitelisting methods. If the exchange desires, it can // perform its own KYC. // - Even after the Crowdsale / ICO if a whitelisted owner tries to sell // their tokens to a non-whitelisted buyer (address), the seller shall be // directed to the KYC process to be whitelisted before the sale can proceed. // This prevents against selling tokens to buyers under embargo. // - If the seller is removed from the whitelist prior to the sale attempt, // the corresponding sale should be reported to the authorities instead of // allowing the seller to proceed. This is subject of further discussion. mapping(address => bool) public whitelist; // If set to true, allow transfers between any addresses regardless of whitelist. // However, sale and/or redemption would still be not allowed regardless of this flag. // In the future, if it is determined that it is legal to transfer but not sell and/or redeem, // we could turn this flag on. bool public isFreeTransferAllowed = false; uint256 public tokenNAVMicroUSD; // Net Asset Value per token in MicroUSD (millionths of 1 US$) uint256 public weiPerUSD; // How many Wei is one US$ // Who's Who address public owner; // The owner of this contract. address public kycAdmin; // The address of the caller which can update the KYC status of an address. address public navAdmin; // The address of the caller which can update the NAV/USD and ETH/USD values. address public crowdsale; //The address of the crowdsale contract. address public redemption; // The address of the redemption contract. address public distributedAutonomousExchange; // The address of the exchange contract. event Mint(address indexed to, uint256 amount); event Burn(uint256 amount); event AddToWhitelist(address indexed beneficiary); event RemoveFromWhitelist(address indexed beneficiary); function PentacoreToken() public { owner = msg.sender; tokenNAVMicroUSD = million; // Initially 1 PENT = 1 US$ (a million millionths) isFreeTransferAllowed = false; isPaused = true; totalSupply_ = 0; // No tokens exist at creation. They are minted as sold. } /** * @dev Throws if called by any account other than the authorized one. * @param authorized the address of the authorized caller. */ modifier onlyBy(address authorized) { require(authorized != address(0)); require(msg.sender == authorized); _; } /** * @dev Pauses / unpauses the transferability of the token. * @param _pause pause if true; unpause if false */ function setPaused(bool _pause) public { require(owner != address(0)); require(msg.sender == owner); isPaused = _pause; } modifier notPaused() { require(!isPaused); _; } /** * @dev Sets the address of the owner. * @param _address The address of the new owner of the Token Contract. */ function transferOwnership(address _address) external onlyBy(owner) { require(_address != address(0)); // Prevent rendering it unusable owner = _address; } /** * @dev Sets the address of the PentacoreCrowdsale contract. * @param _address PentacoreCrowdsale contract address. */ function setKYCAdmin(address _address) external onlyBy(owner) { kycAdmin = _address; } /** * @dev Sets the address of the PentacoreCrowdsale contract. * @param _address PentacoreCrowdsale contract address. */ function setNAVAdmin(address _address) external onlyBy(owner) { navAdmin = _address; } /** * @dev Sets the address of the PentacoreCrowdsale contract. * @param _address PentacoreCrowdsale contract address. */ function setCrowdsaleContract(address _address) external onlyBy(owner) { crowdsale = _address; } /** * @dev Sets the address of the PentacoreRedemption contract. * @param _address PentacoreRedemption contract address. */ function setRedemptionContract(address _address) external onlyBy(owner) { redemption = _address; } /** * @dev Sets the address of the DistributedAutonomousExchange contract. * @param _address DistributedAutonomousExchange contract address. */ function setDistributedAutonomousExchange(address _address) external onlyBy(owner) { distributedAutonomousExchange = _address; } /** * @dev Sets the token price in US$. Set by owner to reflect NAV/token. * @param _price PentacoreToken price in USD. */ function setTokenNAVMicroUSD(uint256 _price) external onlyBy(navAdmin) { tokenNAVMicroUSD = _price; } /** * @dev Sets the token price in US$. Set by owner to reflect NAV/token. * @param _price PentacoreToken price in USD. */ function setWeiPerUSD(uint256 _price) external onlyBy(navAdmin) { weiPerUSD = _price; } /** * @dev Calculate the amount of Wei for a given token amount. The result is rounded down (floored) to a millionth of a US$) * @param _tokenAmount Whole number of tokens to be converted to Wei * @return amount of Wei for the given amount of tokens */ function tokensToWei(uint256 _tokenAmount) public view returns (uint256) { require(tokenNAVMicroUSD != uint256(0)); require(weiPerUSD != uint256(0)); return _tokenAmount.mul(tokenNAVMicroUSD).mul(weiPerUSD).div(million); } /** * @dev Calculate the amount tokens for a given Wei amount and the amount of change in Wei. * @param _weiAmount Whole number of Wei to be converted to tokens * @return whole amount of tokens for the given amount in Wei * @return change in Wei that is not sufficient to buy a whole token */ function weiToTokens(uint256 _weiAmount) public view returns (uint256, uint256) { require(tokenNAVMicroUSD != uint256(0)); require(weiPerUSD != uint256(0)); uint256 tokens = _weiAmount.mul(million).div(weiPerUSD).div(tokenNAVMicroUSD); uint256 changeWei = _weiAmount.sub(tokensToWei(tokens)); return (tokens, changeWei); } /** * @dev Allows / disallows free transferability of tokens regardless of whitelist. * @param _isFreeTransferAllowed disregard whitelist if true; not if false */ function setFreeTransferAllowed(bool _isFreeTransferAllowed) public { require(owner != address(0)); require(msg.sender == owner); isFreeTransferAllowed = _isFreeTransferAllowed; } /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. * @param _beneficiary the address which must be whitelisted by the KYC process in order to pass. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Reverts if beneficiary is not whitelisted and isFreeTransferAllowed is false. Can be used when extending this contract. * @param _beneficiary the address which must be whitelisted by the KYC process in order to pass unless isFreeTransferAllowed. */ modifier isWhitelistedOrFreeTransferAllowed(address _beneficiary) { require(isFreeTransferAllowed || whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) public onlyBy(kycAdmin) { whitelist[_beneficiary] = true; emit AddToWhitelist(_beneficiary); } /** * @dev Adds list of addresses to whitelist. * @param _beneficiaries List of addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyBy(kycAdmin) { for (uint256 i = 0; i < _beneficiaries.length; i++) addToWhitelist(_beneficiaries[i]); } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) public onlyBy(kycAdmin) { whitelist[_beneficiary] = false; emit RemoveFromWhitelist(_beneficiary); } /** * @dev Removes list of addresses from whitelist. * @param _beneficiaries List of addresses to be removed to the whitelist */ function removeManyFromWhitelist(address[] _beneficiaries) external onlyBy(kycAdmin) { for (uint256 i = 0; i < _beneficiaries.length; i++) removeFromWhitelist(_beneficiaries[i]); } /** * @dev Function to mint tokens. We mint as we sell tokens (actually the PentacoreCrowdsale contract does). * @dev The recipient should be whitelisted. * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyBy(crowdsale) isWhitelisted(_to) returns (bool) { // Should run even when the token is paused. require(tokenNAVMicroUSD != uint256(0)); require(weiPerUSD != uint256(0)); require(totalSupply_.add(_amount) <= tokenCap); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); return true; } /** * @dev Function to burn tokens. We burn as owners redeem tokens (actually the PentacoreRedemptions contract does). * @param _amount The amount of tokens to burn. * @return A boolean that indicates if the operation was successful. */ function burn(uint256 _amount) public onlyBy(redemption) returns (bool) { // Should run even when the token is paused. require(balances[redemption].sub(_amount) >= uint256(0)); require(totalSupply_.sub(_amount) >= uint256(0)); balances[redemption] = balances[redemption].sub(_amount); totalSupply_ = totalSupply_.sub(_amount); emit Burn(_amount); return true; } /** * @dev transfer token for a specified address * @dev Both the sender and the recipient should be whitelisted. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public notPaused isWhitelistedOrFreeTransferAllowed(msg.sender) isWhitelistedOrFreeTransferAllowed(_to) returns (bool) { return super.transfer(_to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @dev The sender should be whitelisted. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public notPaused isWhitelistedOrFreeTransferAllowed(msg.sender) returns (bool) { return super.approve(_spender, _value); } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * @dev The sender should be whitelisted. * * 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 notPaused isWhitelistedOrFreeTransferAllowed(msg.sender) returns (bool) { return super.increaseApproval(_spender, _addedValue); } /** * @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 * * @dev The sender does not need to be whitelisted. This is in case they are removed from white list and no longer agree to sell at an exchange. * @dev This function stays untouched (directly inherited), but it's re-defined for clarity: * * @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) { return super.decreaseApproval(_spender, _subtractedValue); } /** * @dev Transfer tokens from one address to another * @dev Both the sender and the recipient should be whitelisted. * @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 notPaused isWhitelistedOrFreeTransferAllowed(_from) isWhitelistedOrFreeTransferAllowed(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } } // File: contracts/PentacoreCrowdsale.sol /** * @title Allows payers to this contract to purchase Pentacore Tokens (PENT). * @author Jordan Stojanovski */ contract PentacoreCrowdsale { using SafeMath for uint256; uint256 public constant million = 1000000; uint256 public constant icoTokenCap = 50 * million; uint256 public constant minimumPurchase = 100; // amount of tokens uint public constant icoDuration = 4 weeks; uint256 public icoStart; bool public postICOSale = false; // The owner of this contracts address public owner; // The token being sold PentacoreToken public token; // Address where funds are collected address public wallet; // Amount of wei raised uint256 public weiRaised; // // Amount raised in various currencies via external sales expressed as currency => valueRaised mapping (bytes32 => uint256) public externalFundsRaised; /** * @dev Sets the address of the owner. * @param _address The address of the new owner of this contract. */ function transferOwnership(address _address) external { require(msg.sender == owner); require(owner != address(0)); require(_address != address(0)); // Prevent rendering it unusable owner = _address; } /** * @dev Sets the address of the wallet where crowdsale prceeds end up. * @param _newWallet The address of the new wallet. */ function changeWallet(address _newWallet) external { require(msg.sender == owner); require(owner != address(0)); require(_newWallet != address(0)); // Prevent rendering it unusable wallet = _newWallet; } /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); /** * Event for external token purchase logging * @param purchaser who paid for the tokens * @param currency currency in which payment was processed * @param value units in specified currency paid for purchase * @param amount amount of tokens purchased * @param txid the transaction ID of the external deposit. Could be a Bitcoin Transaction Hash or Wire Transfer Reference Number. */ event ExternalTokenPurchase(address indexed purchaser, string currency, uint256 value, uint256 amount, uint256 txid); /** * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function PentacoreCrowdsale(address _wallet, PentacoreToken _token) public { owner = msg.sender; require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } function startICO() external { require(owner != address(0)); require(msg.sender == owner); require(token != address(0)); require(icoStart == uint256(0)); icoStart = now; } function isICOActive() public view returns(bool) { return icoStart != 0 && now <= icoStart.add(icoDuration); } function setPostICOSale(bool _postICOSale) public { postICOSale = _postICOSale; } // ----------------------------------------- // PentacoreCrowdsale external interface // ----------------------------------------- /** * @dev fallback function */ function () external payable { buyTokens(); } /** * @dev Token Purchase */ function buyTokens() public payable { require(msg.value != 0); require(msg.sender != 0); require(isICOActive() || postICOSale); require(token.whitelist(msg.sender)); // calculate token amount to be created uint256 tokensPurchased; uint256 weiChange; (tokensPurchased, weiChange) = token.weiToTokens(msg.value); uint256 weiExactAmount = msg.value.sub(weiChange); require(tokensPurchased >= minimumPurchase); // Cannot exceed total allocated supply for the ICO // reverting allows a smaller purchase to pass in the future, up to the icoTokenCap if (isICOActive() && token.totalSupply().add(tokensPurchased) > icoTokenCap) revert(); // Update total amount raised from purchases in Wei weiRaised = weiRaised.add(weiExactAmount); // Issue the tokens token.mint(msg.sender, tokensPurchased); // will revert if tokenCap is reached emit TokenPurchase(msg.sender, weiExactAmount, tokensPurchased); // Process the payment wallet.transfer(weiExactAmount); msg.sender.transfer(weiChange); } /** * @dev This is separated as a function because it can be called separately to avoid costs as it is view only * @param _currency currency symbol * @return the hash of the currency (no security needed - just so it can be mapped) */ function currencyToHash(string _currency) public pure returns(bytes32) { return keccak256(_currency); } /** * @dev This is separated as a function because it can be called separately to avoid costs as it is view only * @param _currency currency symbol * @return the amount of funds externally raised in the given currency */ function getExternalFundsRaised(string _currency) public view returns(uint256) { return externalFundsRaised[currencyToHash(_currency)]; } /** * @dev Token Purchase outside of this contract, usually paid for by currencies other than ETH * @dev Only the owner of this contract can issue tokens in exchange for payments in other currencies * @param _beneficiary the address which receives the tokens * @param _currency currency symbol * @param _value amount paid in the given currency. It must be in whole units, so currencies like MicroUSD (millionth of a US$) should be used * @param _txid the transaction ID of the external deposit. Could be a Bitcoin Transaction Hash or Wire Transfer Reference Number. * @param _amount amount of tokens purchased */ function externalPurchase(address _beneficiary, string _currency, uint256 _value, uint256 _amount, uint256 _txid) public { require(owner != address(0)); require(msg.sender == owner); // Only owner can issue tokens in exchange for external payment require(isICOActive() || postICOSale); require(token.whitelist(_beneficiary)); require(_amount >= minimumPurchase); // Cannot exceed total allocated supply for the ICO // reverting allows a smaller purchase to pass in the future, up to the icoTokenCap if (isICOActive() && token.totalSupply().add(_amount) > icoTokenCap) revert(); // Update total amount raised from purchases via external sales externalFundsRaised[currencyToHash(_currency)] = externalFundsRaised[currencyToHash(_currency)].add(_value); // Issue the tokens token.mint(_beneficiary, _amount); // will revert if tokenCap is reached emit ExternalTokenPurchase(_beneficiary, _currency, _value, _amount, _txid); } }
* @dev Sets the address of the owner. @param _address The address of the new owner of this contract./
function transferOwnership(address _address) external { require(msg.sender == owner); require(owner != address(0)); owner = _address; }
12,546,818
[ 1, 2785, 326, 1758, 434, 326, 3410, 18, 225, 389, 2867, 1021, 1758, 434, 326, 394, 3410, 434, 333, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 5460, 12565, 12, 2867, 389, 2867, 13, 3903, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 565, 2583, 12, 8443, 480, 1758, 12, 20, 10019, 203, 203, 565, 3410, 273, 389, 2867, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; import "./ERC20Capped.sol"; import "./ERC20Burnable.sol"; import "./ERC20Detailed.sol"; import "./ERC20Pausable.sol"; contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable { event NRTManagerAdded(address NRTManager); constructor() public ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) { mint(msg.sender, 910000000000000000000000000); } int256 public timeMachineDepth; // gives the time machine time function mou() public view returns(uint256) { if(timeMachineDepth < 0) { return now - uint256(timeMachineDepth); } else { return now + uint256(timeMachineDepth); } } // sets the time machine depth function setTimeMachineDepth(int256 _timeMachineDepth) public { timeMachineDepth = _timeMachineDepth; } function goToFuture(uint256 _seconds) public { timeMachineDepth += int256(_seconds); } function goToPast(uint256 _seconds) public { timeMachineDepth -= int256(_seconds); } /** * @dev Function to add NRT Manager to have minting rights * It will transfer the minting rights to NRTManager and revokes it from existing minter * @param NRTManager Address of NRT Manager C ontract */ function AddNRTManager(address NRTManager) public onlyMinter returns (bool) { addMinter(NRTManager); addPauser(NRTManager); renounceMinter(); renouncePauser(); emit NRTManagerAdded(NRTManager); return true; } } pragma solidity ^0.5.2; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @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 Transfer token to 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) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } pragma solidity ^0.5.2; import "./ERC20.sol"; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } pragma solidity ^0.5.2; import "./ERC20Mintable.sol"; /** * @title Capped token * @dev Mintable token with a token cap. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; constructor (uint256 cap) public { require(cap > 0); _cap = cap; } /** * @return the cap for the token minting. */ function cap() public view returns (uint256) { return _cap; } function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap); super._mint(account, value); } } pragma solidity ^0.5.2; import "./IERC20.sol"; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.2; import "./ERC20.sol"; import "./MinterRole.sol"; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } pragma solidity ^0.5.2; import "./ERC20.sol"; import "./Pausable.sol"; /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.2; import "./Roles.sol"; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity ^0.5.2; import "./Eraswap.sol"; import "./TimeAlly.sol"; contract NRTManager { using SafeMath for uint256; uint256 public lastNRTRelease; // variable to store last release date uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released uint256 public monthCount; // variable to store the count of months from the intial date uint256 public luckPoolBal; // Luckpool Balance uint256 public burnTokenBal; // tokens to be burned Eraswap token; address Owner; //Eraswap public eraswapToken; // different pool address address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607; address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c; address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E; address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88; address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167; address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9; address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657; address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers address public timeAlly; //address of timeAlly Contract uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address; uint256 public platformMaintenanceBal; // variable to store last NRT released to the address; uint256 public marketingAndRNRBal; // variable to store last NRT released to the address; uint256 public kmPardsBal; // variable to store last NRT released to the address; uint256 public contingencyFundsBal; // variable to store last NRT released to the address; uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address; uint256 public powerTokenNRT; // variable to store last NRT released to the address; uint256 public timeAllyNRT; // variable to store last NRT released to the address; uint256 public timeSwappersNRT; // variable to store last NRT released to the address; // Event to watch NRT distribution // @param NRTReleased The amount of NRT released in the month event NRTDistributed(uint256 NRTReleased); /** * Event to watch Transfer of NRT to different Pool * @param pool - The pool name * @param sendAddress - The address of pool * @param value - The value of NRT released **/ event NRTTransfer(string pool, address sendAddress, uint256 value); // Event to watch Tokens Burned // @param amount The amount burned event TokensBurned(uint256 amount); /** * Event to watch the addition of pool address * @param pool - The pool name * @param sendAddress - The address of pool **/ event PoolAddressAdded(string pool, address sendAddress); // Event to watch LuckPool Updation // @param luckPoolBal The current luckPoolBal event LuckPoolUpdated(uint256 luckPoolBal); // Event to watch BurnTokenBal Updation // @param burnTokenBal The current burnTokenBal event BurnTokenBalUpdated(uint256 burnTokenBal); /** * @dev Throws if caller is not timeAlly */ modifier OnlyAllowed() { require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised"); _; } /** * @dev Throws if caller is not owner */ modifier OnlyOwner() { require(msg.sender == Owner,"Only Owner is authorised"); _; } /** * @dev Should burn tokens according to the total circulation * @return true if success */ function burnTokens() internal returns (bool){ if(burnTokenBal == 0){ return true; } else{ uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month if(MaxAmount >= burnTokenBal ){ token.burn(burnTokenBal); burnTokenBal = 0; } else{ burnTokenBal = burnTokenBal.sub(MaxAmount); token.burn(MaxAmount); } return true; } } /** * @dev To update pool addresses * @param pool - A List of pool addresses * Updates if pool address is not already set and if given address is not zero * @return true if success */ function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){ if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){ newTalentsAndPartnerships = pool[0]; emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships); } if((pool[1] != address(0)) && (platformMaintenance == address(0))){ platformMaintenance = pool[1]; emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance); } if((pool[2] != address(0)) && (marketingAndRNR == address(0))){ marketingAndRNR = pool[2]; emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR); } if((pool[3] != address(0)) && (kmPards == address(0))){ kmPards = pool[3]; emit PoolAddressAdded( "KmPards", kmPards); } if((pool[4] != address(0)) && (contingencyFunds == address(0))){ contingencyFunds = pool[4]; emit PoolAddressAdded( "ContingencyFunds", contingencyFunds); } if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){ researchAndDevelopment = pool[5]; emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment); } if((pool[6] != address(0)) && (powerToken == address(0))){ powerToken = pool[6]; emit PoolAddressAdded( "PowerToken", powerToken); } if((pool[7] != address(0)) && (timeSwappers == address(0))){ timeSwappers = pool[7]; emit PoolAddressAdded( "TimeSwapper", timeSwappers); } if((pool[8] != address(0)) && (timeAlly == address(0))){ timeAlly = pool[8]; emit PoolAddressAdded( "TimeAlly", timeAlly); } return true; } /** * @dev Function to update luckpool balance * @param amount Amount to be updated */ function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){ luckPoolBal = luckPoolBal.add(amount); emit LuckPoolUpdated(luckPoolBal); return true; } /** * @dev Function to trigger to update for burning of tokens * @param amount Amount to be updated */ function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){ burnTokenBal = burnTokenBal.add(amount); emit BurnTokenBalUpdated(burnTokenBal); return true; } /** * @dev To invoke monthly release * @return true if success */ function MonthlyNRTRelease() external returns (bool) { require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month"); uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available. // Calculating NRT to be released to each of the pools newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100); platformMaintenanceBal = (NRTBal.mul(10)).div(100); marketingAndRNRBal = (NRTBal.mul(10)).div(100); kmPardsBal = (NRTBal.mul(10)).div(100); contingencyFundsBal = (NRTBal.mul(10)).div(100); researchAndDevelopmentBal = (NRTBal.mul(5)).div(100); powerTokenNRT = (NRTBal.mul(10)).div(100); timeAllyNRT = (NRTBal.mul(15)).div(100); timeSwappersNRT = (NRTBal.mul(25)).div(100); // sending tokens to respective wallets and emitting events token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal); emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal); token.mint(platformMaintenance,platformMaintenanceBal); emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal); token.mint(marketingAndRNR,marketingAndRNRBal); emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal); token.mint(kmPards,kmPardsBal); emit NRTTransfer("kmPards", kmPards, kmPardsBal); token.mint(contingencyFunds,contingencyFundsBal); emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal); token.mint(researchAndDevelopment,researchAndDevelopmentBal); emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal); token.mint(powerToken,powerTokenNRT); emit NRTTransfer("powerToken", powerToken, powerTokenNRT); token.mint(timeAlly,timeAllyNRT); TimeAlly timeAllyContract = TimeAlly(timeAlly); timeAllyContract.increaseMonth(timeAllyNRT); emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT); token.mint(timeSwappers,timeSwappersNRT); emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT); // Reseting NRT emit NRTDistributed(NRTBal); luckPoolBal = 0; lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days burnTokens(); // burning burnTokenBal emit TokensBurned(burnTokenBal); if(monthCount == 11){ monthCount = 0; annualNRTAmount = (annualNRTAmount.mul(90)).div(100); monthlyNRTAmount = annualNRTAmount.div(12); } else{ monthCount = monthCount.add(1); } return true; } /** * @dev Constructor */ constructor(address eraswaptoken) public{ token = Eraswap(eraswaptoken); lastNRTRelease = now; annualNRTAmount = 819000000000000000000000000; monthlyNRTAmount = annualNRTAmount.div(uint256(12)); monthCount = 0; Owner = msg.sender; } } pragma solidity ^0.5.2; import "./PauserRole.sol"; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @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 onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } pragma solidity ^0.5.2; import "./Roles.sol"; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @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; } /** * @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 unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.5.10; import './SafeMath.sol'; import './Eraswap.sol'; import './NRTManager.sol'; /* Potential bugs: this contract is designed assuming NRT Release will happen every month. There might be issues when the NRT scheduled - added stakingMonth property in Staking struct fix withdraw fractionFrom15 luck pool - done add loanactive contition to take loan - done ensure stakingMonth in the struct is being used every where instead of calculation - done remove local variables uncesessary final the earthSecondsInMonth amount in TimeAlly as well in NRT add events for required functions */ /// @author The EraSwap Team /// @title TimeAlly Smart Contract /// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee contract TimeAlly { using SafeMath for uint256; struct Staking { uint256 exaEsAmount; uint256 timestamp; uint256 stakingMonth; uint256 stakingPlanId; uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode uint256 loanId; uint256 totalNominationShares; mapping (uint256 => bool) isMonthClaimed; mapping (address => uint256) nomination; } struct StakingPlan { uint256 months; uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT // bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan. bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months } struct Loan { uint256 exaEsAmount; uint256 timestamp; uint256 loanPlanId; uint256 status; // @dev 1 => not repayed yet; 2 => repayed uint256[] stakingIds; } struct LoanPlan { uint256 loanMonths; uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan } uint256 public deployedTimestamp; address public owner; Eraswap public token; NRTManager public nrtManager; /// @dev 1 Year = 365.242 days for taking care of leap years uint256 public earthSecondsInMonth = 2629744; // uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year StakingPlan[] public stakingPlans; LoanPlan[] public loanPlans; // user activity details: mapping(address => Staking[]) public stakings; mapping(address => Loan[]) public loans; mapping(address => uint256) public launchReward; /// @dev TimeAlly month to exaEsAmount mapping. mapping (uint256 => uint256) public totalActiveStakings; /// @notice NRT being received from NRT Manager every month is stored in this array /// @dev current month is the length of this array uint256[] public timeAllyMonthlyNRT; event NewStaking ( address indexed _userAddress, uint256 indexed _stakePlanId, uint256 _exaEsAmount, uint256 _stakingId ); event PrincipalWithdrawl ( address indexed _userAddress, uint256 _stakingId ); event NomineeNew ( address indexed _userAddress, uint256 indexed _stakingId, address indexed _nomineeAddress ); event NomineeWithdraw ( address indexed _userAddress, uint256 indexed _stakingId, address indexed _nomineeAddress, uint256 _liquid, uint256 _accrued ); event BenefitWithdrawl ( address indexed _userAddress, uint256 _stakingId, uint256[] _months, uint256 _halfBenefit ); event NewLoan ( address indexed _userAddress, uint256 indexed _loanPlanId, uint256 _exaEsAmount, uint256 _loanInterest, uint256 _loanId ); event RepayLoan ( address indexed _userAddress, uint256 _loanId ); modifier onlyNRTManager() { require( msg.sender == address(nrtManager) // , 'only NRT manager can call' ); _; } modifier onlyOwner() { require( msg.sender == owner // , 'only deployer can call' ); _; } /// @notice sets up TimeAlly contract when deployed /// @param _tokenAddress - is EraSwap contract address /// @param _nrtAddress - is NRT Manager contract address constructor(address _tokenAddress, address _nrtAddress) public { owner = msg.sender; token = Eraswap(_tokenAddress); nrtManager = NRTManager(_nrtAddress); deployedTimestamp = now; timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released } /// @notice this function is used by NRT manager to communicate NRT release to TimeAlly function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager { timeAllyMonthlyNRT.push(_timeAllyNRT); } /// @notice TimeAlly month is dependent on the monthly NRT release /// @return current month is the TimeAlly month function getCurrentMonth() public view returns (uint256) { return timeAllyMonthlyNRT.length - 1; } /// @notice this function is used by owner to create plans for new stakings /// @param _months - is number of staking months of a plan. for eg. 12 months /// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool /// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner { stakingPlans.push(StakingPlan({ months: _months, fractionFrom15: _fractionFrom15, // isPlanActive: true, isUrgentLoanAllowed: _isUrgentLoanAllowed })); } /// @notice this function is used by owner to create plans for new loans /// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period /// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner { require(_maxLoanAmountPercent <= 100 // , 'everyone should not be able to take loan more than 100 percent of their stakings' ); loanPlans.push(LoanPlan({ loanMonths: _loanMonths, loanRate: _loanRate, maxLoanAmountPercent: _maxLoanAmountPercent })); } /// @notice takes ES from user and locks it for a time according to plan selected by user /// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake /// @param _stakingPlanId - plan for staking function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public { /// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase require(_exaEsAmount > 0 // , 'staking amount should be non zero' ); require(token.transferFrom(msg.sender, address(this), _exaEsAmount) // , 'could not transfer tokens' ); uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months; // @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs for( uint256 month = getCurrentMonth() + 1; month <= stakeEndMonth; month++ ) { totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount); } stakings[msg.sender].push(Staking({ exaEsAmount: _exaEsAmount, timestamp: now, stakingMonth: getCurrentMonth(), stakingPlanId: _stakingPlanId, status: 1, loanId: 0, totalNominationShares: 0 })); emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1); } /// @notice this function is used to see total stakings of any user of TimeAlly /// @param _userAddress - address of user /// @return number of stakings of _userAddress function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) { return stakings[_userAddress].length; } /// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking. /// @dev Allowance is required before topup. /// @param _exaEsAmount - amount to add to your rewards for sending rewards to others function topupRewardBucket(uint256 _exaEsAmount) public { require(token.transferFrom(msg.sender, address(this), _exaEsAmount)); launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount); } /// @notice this function is used to send rewards to multiple users /// @param _addresses - array of address to send rewards /// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner { for(uint256 i = 0; i < _addresses.length; i++) { launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]); launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]); } } /// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards /// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings function claimLaunchReward(uint256 _stakingPlanId) public { // require(stakingPlans[_stakingPlanId].isPlanActive // // , 'selected plan is not active' // ); require(launchReward[msg.sender] > 0 // , 'launch reward should be non zero' ); uint256 reward = launchReward[msg.sender]; launchReward[msg.sender] = 0; // @dev logic similar to newStaking function uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months; // @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs for( uint256 month = getCurrentMonth() + 1; month <= stakeEndMonth; month++ ) { totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option } stakings[msg.sender].push(Staking({ exaEsAmount: reward, timestamp: now, stakingMonth: getCurrentMonth(), stakingPlanId: _stakingPlanId, status: 1, loanId: 0, totalNominationShares: 0 })); emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1); } /// @notice used internally to see if staking is active or not. does not include if staking is claimed. /// @param _userAddress - address of user /// @param _stakingId - staking id /// @param _atMonth - particular month to check staking active /// @return true is staking is in correct time frame and also no loan on it function isStakingActive( address _userAddress, uint256 _stakingId, uint256 _atMonth ) public view returns (bool) { //uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth); return ( /// @dev _atMonth should be a month after which staking starts stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth /// @dev _atMonth should be a month before which staking ends && stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth /// @dev staking should have active status && stakings[_userAddress][_stakingId].status == 1 /// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking && ( getCurrentMonth() != _atMonth || now >= stakings[_userAddress][_stakingId].timestamp .add( getCurrentMonth() .sub(stakings[_userAddress][_stakingId].stakingMonth) .mul(earthSecondsInMonth) ) ) ); } /// @notice this function is used for seeing the benefits of a staking of any user /// @param _userAddress - address of user /// @param _stakingId - staking id /// @param _months - array of months user is interested to see benefits. /// @return amount of ExaES of benefits of entered months function seeBenefitOfAStakingByMonths( address _userAddress, uint256 _stakingId, uint256[] memory _months ) public view returns (uint256) { uint256 benefitOfAllMonths; for(uint256 i = 0; i < _months.length; i++) { /// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function. // require( // isStakingActive(_userAddress, _stakingId, _months[i]) // && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]] // // , 'staking must be active' // ); if(isStakingActive(_userAddress, _stakingId, _months[i]) && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) { uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount .mul(timeAllyMonthlyNRT[ _months[i] ]) .div(totalActiveStakings[ _months[i] ]); benefitOfAllMonths = benefitOfAllMonths.add(benefit); } } return benefitOfAllMonths.mul( stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15 ).div(15); } /// @notice this function is used for withdrawing the benefits of a staking of any user /// @param _stakingId - staking id /// @param _months - array of months user is interested to withdraw benefits of staking. function withdrawBenefitOfAStakingByMonths( uint256 _stakingId, uint256[] memory _months ) public { uint256 _benefitOfAllMonths; for(uint256 i = 0; i < _months.length; i++) { // require( // isStakingActive(msg.sender, _stakingId, _months[i]) // && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] // // , 'staking must be active' // ); if(isStakingActive(msg.sender, _stakingId, _months[i]) && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) { uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount .mul(timeAllyMonthlyNRT[ _months[i] ]) .div(totalActiveStakings[ _months[i] ]); _benefitOfAllMonths = _benefitOfAllMonths.add(_benefit); stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true; } } uint256 _luckPool = _benefitOfAllMonths .mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) ) .div( 15 ); require( token.transfer(address(nrtManager), _luckPool) ); require( nrtManager.UpdateLuckpool(_luckPool) ); _benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool); uint256 _halfBenefit = _benefitOfAllMonths.div(2); require( token.transfer(msg.sender, _halfBenefit) ); launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit); // emit event emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit); } /// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed /// @param _stakingIds - input which stakings to withdraw function withdrawExpiredStakings(uint256[] memory _stakingIds) public { for(uint256 i = 0; i < _stakingIds.length; i++) { require(now >= stakings[msg.sender][_stakingIds[i]].timestamp .add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth)) // , 'cannot withdraw before staking ends' ); stakings[msg.sender][_stakingIds[i]].status = 3; token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount); emit PrincipalWithdrawl(msg.sender, _stakingIds[i]); } } /// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings /// @param _userAddress - address of user /// @param _stakingIds - array of staking ids which should be used to estimate max loan amount /// @param _loanPlanId - the loan plan user wishes to take loan. /// @return max loaning amount function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) { uint256 _currentMonth = getCurrentMonth(); //require(_currentMonth >= _atMonth, 'cannot see future stakings'); uint256 userStakingsExaEsAmount; for(uint256 i = 0; i < _stakingIds.length; i++) { if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth) && ( // @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75% stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed || now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100) ) ) { userStakingsExaEsAmount = userStakingsExaEsAmount .add(stakings[_userAddress][_stakingIds[i]].exaEsAmount .mul(loanPlans[_loanPlanId].maxLoanAmountPercent) .div(100) // .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15) // .div(15) ); } } return userStakingsExaEsAmount; //.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100); } /// @notice this function is used to take loan on multiple stakings /// @param _loanPlanId - user can select this plan which defines loan duration and loan interest /// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited /// @param _stakingIds - staking ids user wishes to encash for taking the loan function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public { // @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period uint256 _currentMonth = getCurrentMonth(); uint256 _userStakingsExaEsAmount; for(uint256 i = 0; i < _stakingIds.length; i++) { if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth) && ( // @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75% stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed || now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100) ) ) { // @dev store sum in a number _userStakingsExaEsAmount = _userStakingsExaEsAmount .add( stakings[msg.sender][ _stakingIds[i] ].exaEsAmount .mul(loanPlans[_loanPlanId].maxLoanAmountPercent) .div(100) ); // @dev subtract total active stakings uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth; uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months; for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) { totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount); } // @dev make stakings inactive for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) { stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true; stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan } } } uint256 _maxLoaningAmount = _userStakingsExaEsAmount; if(_exaEsAmount > _maxLoaningAmount) { require(false // , 'cannot loan more than maxLoaningAmount' ); } uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100); uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest); require( token.transfer(address(nrtManager), _loanInterest) ); require( nrtManager.UpdateLuckpool(_loanInterest) ); loans[msg.sender].push(Loan({ exaEsAmount: _exaEsAmount, timestamp: now, loanPlanId: _loanPlanId, status: 1, stakingIds: _stakingIds })); // @dev send user amount require( token.transfer(msg.sender, _loanAmountToTransfer) ); emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1); } /// @notice repay loan functionality /// @dev need to give allowance before this /// @param _loanId - select loan to repay function repayLoanSelf(uint256 _loanId) public { require(loans[msg.sender][_loanId].status == 1 // , 'can only repay pending loans' ); require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now // , 'cannot repay expired loan' ); require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount) // , 'cannot receive enough tokens, please check if allowance is there' ); loans[msg.sender][_loanId].status = 2; // @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) { uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i]; stakings[msg.sender][_stakingId].status = 1; uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth); uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months; for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) { stakings[msg.sender][_stakingId].isMonthClaimed[i] = false; totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount); } } // add repay event emit RepayLoan(msg.sender, _loanId); } function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public { uint256 _amountToBurn; for(uint256 i = 0; i < _addressArray.length; i++) { require( loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1 // , 'loan should not be repayed' ); require( now > loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp + loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth) // , 'loan should have crossed its loan period' ); uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds; /// @dev add staking amounts of all stakings on which loan is taken for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) { _amountToBurn = _amountToBurn.add( stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount ); } /// @dev sub loan amount _amountToBurn = _amountToBurn.sub( loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount ); } require(token.transfer(address(nrtManager), _amountToBurn)); require(nrtManager.UpdateBurnBal(_amountToBurn)); // emit event } /// @notice this function is used to add nominee to a staking /// @param _stakingId - staking id /// @param _nomineeAddress - address of nominee to be added to staking /// @param _shares - amount of shares of the staking to the nominee /// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it. function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public { require(stakings[msg.sender][_stakingId].status == 1 // , 'staking should active' ); require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0 // , 'should not be nominee already' ); stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares); stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares; emit NomineeNew(msg.sender, _stakingId, _nomineeAddress); } /// @notice this function is used to read the nomination of a nominee address of a staking of a user /// @param _userAddress - address of staking owner /// @param _stakingId - staking id /// @param _nomineeAddress - address of nominee /// @return nomination of the nominee function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) { return stakings[_userAddress][_stakingId].nomination[_nomineeAddress]; } // /// @notice this function is used to update nomination of a nominee of sender's staking // /// @param _stakingId - staking id // /// @param _nomineeAddress - address of nominee // /// @param _shares - shares to be updated for the nominee // function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public { // require(stakings[msg.sender][_stakingId].status == 1 // // , 'staking should active' // ); // uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress]; // if(_shares > _oldShares) { // uint256 _diff = _shares.sub(_oldShares); // stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff); // stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff); // } else if(_shares < _oldShares) { // uint256 _diff = _oldShares.sub(_shares); // stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff); // stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff); // } // } /// @notice this function is used to remove nomination of a address /// @param _stakingId - staking id /// @param _nomineeAddress - address of nominee function removeNominee(uint256 _stakingId, address _nomineeAddress) public { require(stakings[msg.sender][_stakingId].status == 1, 'staking should active'); uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender]; stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0; stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares); } /// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking /// @param _userAddress - address of user /// @param _stakingId - staking id function nomineeWithdraw(address _userAddress, uint256 _stakingId) public { // end time stamp > 0 uint256 currentTime = now; require( currentTime > (stakings[_userAddress][_stakingId].timestamp + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth + 12 * earthSecondsInMonth ) // , 'cannot nominee withdraw before ' ); uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender]; require(_nomineeShares > 0 // , 'Not a nominee of this staking' ); //uint256 _totalShares = ; // set staking to nomination mode if it isn't. if(stakings[_userAddress][_stakingId].status != 5) { stakings[_userAddress][_stakingId].status = 5; } // adding principal account uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount; uint256 _pendingAccruedAmountInStaking; // uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth); uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months; // adding monthly benefits which are not claimed for( uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth; i < _stakeEndMonth; i++ ) { if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) { uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount .mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15) .div(15); uint256 _monthlyBenefit = _effectiveAmount .mul(timeAllyMonthlyNRT[i]) .div(totalActiveStakings[i]); _pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2)); _pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2)); } } // now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking // on which user's share will be calculated and sent // marking nominee as claimed by removing his shares stakings[_userAddress][_stakingId].nomination[msg.sender] = 0; uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking .mul(_nomineeShares) .div(stakings[_userAddress][_stakingId].totalNominationShares); token.transfer(msg.sender, _nomineeLiquidShare); uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking .mul(_nomineeShares) .div(stakings[_userAddress][_stakingId].totalNominationShares); launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare); // emit a event emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare); } } pragma solidity ^0.5.2; import "./ERC20Capped.sol"; import "./ERC20Burnable.sol"; import "./ERC20Detailed.sol"; import "./ERC20Pausable.sol"; contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable { event NRTManagerAdded(address NRTManager); constructor() public ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) { mint(msg.sender, 910000000000000000000000000); } int256 public timeMachineDepth; // gives the time machine time function mou() public view returns(uint256) { if(timeMachineDepth < 0) { return now - uint256(timeMachineDepth); } else { return now + uint256(timeMachineDepth); } } // sets the time machine depth function setTimeMachineDepth(int256 _timeMachineDepth) public { timeMachineDepth = _timeMachineDepth; } function goToFuture(uint256 _seconds) public { timeMachineDepth += int256(_seconds); } function goToPast(uint256 _seconds) public { timeMachineDepth -= int256(_seconds); } /** * @dev Function to add NRT Manager to have minting rights * It will transfer the minting rights to NRTManager and revokes it from existing minter * @param NRTManager Address of NRT Manager C ontract */ function AddNRTManager(address NRTManager) public onlyMinter returns (bool) { addMinter(NRTManager); addPauser(NRTManager); renounceMinter(); renouncePauser(); emit NRTManagerAdded(NRTManager); return true; } } pragma solidity ^0.5.2; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @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 Transfer token to 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) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } pragma solidity ^0.5.2; import "./ERC20.sol"; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } pragma solidity ^0.5.2; import "./ERC20Mintable.sol"; /** * @title Capped token * @dev Mintable token with a token cap. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; constructor (uint256 cap) public { require(cap > 0); _cap = cap; } /** * @return the cap for the token minting. */ function cap() public view returns (uint256) { return _cap; } function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap); super._mint(account, value); } } pragma solidity ^0.5.2; import "./IERC20.sol"; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.2; import "./ERC20.sol"; import "./MinterRole.sol"; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } pragma solidity ^0.5.2; import "./ERC20.sol"; import "./Pausable.sol"; /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.2; import "./Roles.sol"; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity ^0.5.2; import "./Eraswap.sol"; import "./TimeAlly.sol"; contract NRTManager { using SafeMath for uint256; uint256 public lastNRTRelease; // variable to store last release date uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released uint256 public monthCount; // variable to store the count of months from the intial date uint256 public luckPoolBal; // Luckpool Balance uint256 public burnTokenBal; // tokens to be burned Eraswap token; address Owner; //Eraswap public eraswapToken; // different pool address address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607; address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c; address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E; address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88; address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167; address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9; address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657; address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers address public timeAlly; //address of timeAlly Contract uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address; uint256 public platformMaintenanceBal; // variable to store last NRT released to the address; uint256 public marketingAndRNRBal; // variable to store last NRT released to the address; uint256 public kmPardsBal; // variable to store last NRT released to the address; uint256 public contingencyFundsBal; // variable to store last NRT released to the address; uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address; uint256 public powerTokenNRT; // variable to store last NRT released to the address; uint256 public timeAllyNRT; // variable to store last NRT released to the address; uint256 public timeSwappersNRT; // variable to store last NRT released to the address; // Event to watch NRT distribution // @param NRTReleased The amount of NRT released in the month event NRTDistributed(uint256 NRTReleased); /** * Event to watch Transfer of NRT to different Pool * @param pool - The pool name * @param sendAddress - The address of pool * @param value - The value of NRT released **/ event NRTTransfer(string pool, address sendAddress, uint256 value); // Event to watch Tokens Burned // @param amount The amount burned event TokensBurned(uint256 amount); /** * Event to watch the addition of pool address * @param pool - The pool name * @param sendAddress - The address of pool **/ event PoolAddressAdded(string pool, address sendAddress); // Event to watch LuckPool Updation // @param luckPoolBal The current luckPoolBal event LuckPoolUpdated(uint256 luckPoolBal); // Event to watch BurnTokenBal Updation // @param burnTokenBal The current burnTokenBal event BurnTokenBalUpdated(uint256 burnTokenBal); /** * @dev Throws if caller is not timeAlly */ modifier OnlyAllowed() { require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised"); _; } /** * @dev Throws if caller is not owner */ modifier OnlyOwner() { require(msg.sender == Owner,"Only Owner is authorised"); _; } /** * @dev Should burn tokens according to the total circulation * @return true if success */ function burnTokens() internal returns (bool){ if(burnTokenBal == 0){ return true; } else{ uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month if(MaxAmount >= burnTokenBal ){ token.burn(burnTokenBal); burnTokenBal = 0; } else{ burnTokenBal = burnTokenBal.sub(MaxAmount); token.burn(MaxAmount); } return true; } } /** * @dev To update pool addresses * @param pool - A List of pool addresses * Updates if pool address is not already set and if given address is not zero * @return true if success */ function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){ if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){ newTalentsAndPartnerships = pool[0]; emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships); } if((pool[1] != address(0)) && (platformMaintenance == address(0))){ platformMaintenance = pool[1]; emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance); } if((pool[2] != address(0)) && (marketingAndRNR == address(0))){ marketingAndRNR = pool[2]; emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR); } if((pool[3] != address(0)) && (kmPards == address(0))){ kmPards = pool[3]; emit PoolAddressAdded( "KmPards", kmPards); } if((pool[4] != address(0)) && (contingencyFunds == address(0))){ contingencyFunds = pool[4]; emit PoolAddressAdded( "ContingencyFunds", contingencyFunds); } if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){ researchAndDevelopment = pool[5]; emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment); } if((pool[6] != address(0)) && (powerToken == address(0))){ powerToken = pool[6]; emit PoolAddressAdded( "PowerToken", powerToken); } if((pool[7] != address(0)) && (timeSwappers == address(0))){ timeSwappers = pool[7]; emit PoolAddressAdded( "TimeSwapper", timeSwappers); } if((pool[8] != address(0)) && (timeAlly == address(0))){ timeAlly = pool[8]; emit PoolAddressAdded( "TimeAlly", timeAlly); } return true; } /** * @dev Function to update luckpool balance * @param amount Amount to be updated */ function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){ luckPoolBal = luckPoolBal.add(amount); emit LuckPoolUpdated(luckPoolBal); return true; } /** * @dev Function to trigger to update for burning of tokens * @param amount Amount to be updated */ function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){ burnTokenBal = burnTokenBal.add(amount); emit BurnTokenBalUpdated(burnTokenBal); return true; } /** * @dev To invoke monthly release * @return true if success */ function MonthlyNRTRelease() external returns (bool) { require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month"); uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available. // Calculating NRT to be released to each of the pools newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100); platformMaintenanceBal = (NRTBal.mul(10)).div(100); marketingAndRNRBal = (NRTBal.mul(10)).div(100); kmPardsBal = (NRTBal.mul(10)).div(100); contingencyFundsBal = (NRTBal.mul(10)).div(100); researchAndDevelopmentBal = (NRTBal.mul(5)).div(100); powerTokenNRT = (NRTBal.mul(10)).div(100); timeAllyNRT = (NRTBal.mul(15)).div(100); timeSwappersNRT = (NRTBal.mul(25)).div(100); // sending tokens to respective wallets and emitting events token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal); emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal); token.mint(platformMaintenance,platformMaintenanceBal); emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal); token.mint(marketingAndRNR,marketingAndRNRBal); emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal); token.mint(kmPards,kmPardsBal); emit NRTTransfer("kmPards", kmPards, kmPardsBal); token.mint(contingencyFunds,contingencyFundsBal); emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal); token.mint(researchAndDevelopment,researchAndDevelopmentBal); emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal); token.mint(powerToken,powerTokenNRT); emit NRTTransfer("powerToken", powerToken, powerTokenNRT); token.mint(timeAlly,timeAllyNRT); TimeAlly timeAllyContract = TimeAlly(timeAlly); timeAllyContract.increaseMonth(timeAllyNRT); emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT); token.mint(timeSwappers,timeSwappersNRT); emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT); // Reseting NRT emit NRTDistributed(NRTBal); luckPoolBal = 0; lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days burnTokens(); // burning burnTokenBal emit TokensBurned(burnTokenBal); if(monthCount == 11){ monthCount = 0; annualNRTAmount = (annualNRTAmount.mul(90)).div(100); monthlyNRTAmount = annualNRTAmount.div(12); } else{ monthCount = monthCount.add(1); } return true; } /** * @dev Constructor */ constructor(address eraswaptoken) public{ token = Eraswap(eraswaptoken); lastNRTRelease = now; annualNRTAmount = 819000000000000000000000000; monthlyNRTAmount = annualNRTAmount.div(uint256(12)); monthCount = 0; Owner = msg.sender; } } pragma solidity ^0.5.2; import "./PauserRole.sol"; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @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 onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } pragma solidity ^0.5.2; import "./Roles.sol"; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @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; } /** * @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 unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.5.10; import './SafeMath.sol'; import './Eraswap.sol'; import './NRTManager.sol'; /* Potential bugs: this contract is designed assuming NRT Release will happen every month. There might be issues when the NRT scheduled - added stakingMonth property in Staking struct fix withdraw fractionFrom15 luck pool - done add loanactive contition to take loan - done ensure stakingMonth in the struct is being used every where instead of calculation - done remove local variables uncesessary final the earthSecondsInMonth amount in TimeAlly as well in NRT add events for required functions */ /// @author The EraSwap Team /// @title TimeAlly Smart Contract /// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee contract TimeAlly { using SafeMath for uint256; struct Staking { uint256 exaEsAmount; uint256 timestamp; uint256 stakingMonth; uint256 stakingPlanId; uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode uint256 loanId; uint256 totalNominationShares; mapping (uint256 => bool) isMonthClaimed; mapping (address => uint256) nomination; } struct StakingPlan { uint256 months; uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT // bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan. bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months } struct Loan { uint256 exaEsAmount; uint256 timestamp; uint256 loanPlanId; uint256 status; // @dev 1 => not repayed yet; 2 => repayed uint256[] stakingIds; } struct LoanPlan { uint256 loanMonths; uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan } uint256 public deployedTimestamp; address public owner; Eraswap public token; NRTManager public nrtManager; /// @dev 1 Year = 365.242 days for taking care of leap years uint256 public earthSecondsInMonth = 2629744; // uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year StakingPlan[] public stakingPlans; LoanPlan[] public loanPlans; // user activity details: mapping(address => Staking[]) public stakings; mapping(address => Loan[]) public loans; mapping(address => uint256) public launchReward; /// @dev TimeAlly month to exaEsAmount mapping. mapping (uint256 => uint256) public totalActiveStakings; /// @notice NRT being received from NRT Manager every month is stored in this array /// @dev current month is the length of this array uint256[] public timeAllyMonthlyNRT; event NewStaking ( address indexed _userAddress, uint256 indexed _stakePlanId, uint256 _exaEsAmount, uint256 _stakingId ); event PrincipalWithdrawl ( address indexed _userAddress, uint256 _stakingId ); event NomineeNew ( address indexed _userAddress, uint256 indexed _stakingId, address indexed _nomineeAddress ); event NomineeWithdraw ( address indexed _userAddress, uint256 indexed _stakingId, address indexed _nomineeAddress, uint256 _liquid, uint256 _accrued ); event BenefitWithdrawl ( address indexed _userAddress, uint256 _stakingId, uint256[] _months, uint256 _halfBenefit ); event NewLoan ( address indexed _userAddress, uint256 indexed _loanPlanId, uint256 _exaEsAmount, uint256 _loanInterest, uint256 _loanId ); event RepayLoan ( address indexed _userAddress, uint256 _loanId ); modifier onlyNRTManager() { require( msg.sender == address(nrtManager) // , 'only NRT manager can call' ); _; } modifier onlyOwner() { require( msg.sender == owner // , 'only deployer can call' ); _; } /// @notice sets up TimeAlly contract when deployed /// @param _tokenAddress - is EraSwap contract address /// @param _nrtAddress - is NRT Manager contract address constructor(address _tokenAddress, address _nrtAddress) public { owner = msg.sender; token = Eraswap(_tokenAddress); nrtManager = NRTManager(_nrtAddress); deployedTimestamp = now; timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released } /// @notice this function is used by NRT manager to communicate NRT release to TimeAlly function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager { timeAllyMonthlyNRT.push(_timeAllyNRT); } /// @notice TimeAlly month is dependent on the monthly NRT release /// @return current month is the TimeAlly month function getCurrentMonth() public view returns (uint256) { return timeAllyMonthlyNRT.length - 1; } /// @notice this function is used by owner to create plans for new stakings /// @param _months - is number of staking months of a plan. for eg. 12 months /// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool /// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner { stakingPlans.push(StakingPlan({ months: _months, fractionFrom15: _fractionFrom15, // isPlanActive: true, isUrgentLoanAllowed: _isUrgentLoanAllowed })); } /// @notice this function is used by owner to create plans for new loans /// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period /// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner { require(_maxLoanAmountPercent <= 100 // , 'everyone should not be able to take loan more than 100 percent of their stakings' ); loanPlans.push(LoanPlan({ loanMonths: _loanMonths, loanRate: _loanRate, maxLoanAmountPercent: _maxLoanAmountPercent })); } /// @notice takes ES from user and locks it for a time according to plan selected by user /// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake /// @param _stakingPlanId - plan for staking function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public { /// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase require(_exaEsAmount > 0 // , 'staking amount should be non zero' ); require(token.transferFrom(msg.sender, address(this), _exaEsAmount) // , 'could not transfer tokens' ); uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months; // @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs for( uint256 month = getCurrentMonth() + 1; month <= stakeEndMonth; month++ ) { totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount); } stakings[msg.sender].push(Staking({ exaEsAmount: _exaEsAmount, timestamp: now, stakingMonth: getCurrentMonth(), stakingPlanId: _stakingPlanId, status: 1, loanId: 0, totalNominationShares: 0 })); emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1); } /// @notice this function is used to see total stakings of any user of TimeAlly /// @param _userAddress - address of user /// @return number of stakings of _userAddress function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) { return stakings[_userAddress].length; } /// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking. /// @dev Allowance is required before topup. /// @param _exaEsAmount - amount to add to your rewards for sending rewards to others function topupRewardBucket(uint256 _exaEsAmount) public { require(token.transferFrom(msg.sender, address(this), _exaEsAmount)); launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount); } /// @notice this function is used to send rewards to multiple users /// @param _addresses - array of address to send rewards /// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner { for(uint256 i = 0; i < _addresses.length; i++) { launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]); launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]); } } /// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards /// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings function claimLaunchReward(uint256 _stakingPlanId) public { // require(stakingPlans[_stakingPlanId].isPlanActive // // , 'selected plan is not active' // ); require(launchReward[msg.sender] > 0 // , 'launch reward should be non zero' ); uint256 reward = launchReward[msg.sender]; launchReward[msg.sender] = 0; // @dev logic similar to newStaking function uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months; // @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs for( uint256 month = getCurrentMonth() + 1; month <= stakeEndMonth; month++ ) { totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option } stakings[msg.sender].push(Staking({ exaEsAmount: reward, timestamp: now, stakingMonth: getCurrentMonth(), stakingPlanId: _stakingPlanId, status: 1, loanId: 0, totalNominationShares: 0 })); emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1); } /// @notice used internally to see if staking is active or not. does not include if staking is claimed. /// @param _userAddress - address of user /// @param _stakingId - staking id /// @param _atMonth - particular month to check staking active /// @return true is staking is in correct time frame and also no loan on it function isStakingActive( address _userAddress, uint256 _stakingId, uint256 _atMonth ) public view returns (bool) { //uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth); return ( /// @dev _atMonth should be a month after which staking starts stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth /// @dev _atMonth should be a month before which staking ends && stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth /// @dev staking should have active status && stakings[_userAddress][_stakingId].status == 1 /// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking && ( getCurrentMonth() != _atMonth || now >= stakings[_userAddress][_stakingId].timestamp .add( getCurrentMonth() .sub(stakings[_userAddress][_stakingId].stakingMonth) .mul(earthSecondsInMonth) ) ) ); } /// @notice this function is used for seeing the benefits of a staking of any user /// @param _userAddress - address of user /// @param _stakingId - staking id /// @param _months - array of months user is interested to see benefits. /// @return amount of ExaES of benefits of entered months function seeBenefitOfAStakingByMonths( address _userAddress, uint256 _stakingId, uint256[] memory _months ) public view returns (uint256) { uint256 benefitOfAllMonths; for(uint256 i = 0; i < _months.length; i++) { /// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function. // require( // isStakingActive(_userAddress, _stakingId, _months[i]) // && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]] // // , 'staking must be active' // ); if(isStakingActive(_userAddress, _stakingId, _months[i]) && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) { uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount .mul(timeAllyMonthlyNRT[ _months[i] ]) .div(totalActiveStakings[ _months[i] ]); benefitOfAllMonths = benefitOfAllMonths.add(benefit); } } return benefitOfAllMonths.mul( stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15 ).div(15); } /// @notice this function is used for withdrawing the benefits of a staking of any user /// @param _stakingId - staking id /// @param _months - array of months user is interested to withdraw benefits of staking. function withdrawBenefitOfAStakingByMonths( uint256 _stakingId, uint256[] memory _months ) public { uint256 _benefitOfAllMonths; for(uint256 i = 0; i < _months.length; i++) { // require( // isStakingActive(msg.sender, _stakingId, _months[i]) // && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] // // , 'staking must be active' // ); if(isStakingActive(msg.sender, _stakingId, _months[i]) && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) { uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount .mul(timeAllyMonthlyNRT[ _months[i] ]) .div(totalActiveStakings[ _months[i] ]); _benefitOfAllMonths = _benefitOfAllMonths.add(_benefit); stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true; } } uint256 _luckPool = _benefitOfAllMonths .mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) ) .div( 15 ); require( token.transfer(address(nrtManager), _luckPool) ); require( nrtManager.UpdateLuckpool(_luckPool) ); _benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool); uint256 _halfBenefit = _benefitOfAllMonths.div(2); require( token.transfer(msg.sender, _halfBenefit) ); launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit); // emit event emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit); } /// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed /// @param _stakingIds - input which stakings to withdraw function withdrawExpiredStakings(uint256[] memory _stakingIds) public { for(uint256 i = 0; i < _stakingIds.length; i++) { require(now >= stakings[msg.sender][_stakingIds[i]].timestamp .add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth)) // , 'cannot withdraw before staking ends' ); stakings[msg.sender][_stakingIds[i]].status = 3; token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount); emit PrincipalWithdrawl(msg.sender, _stakingIds[i]); } } /// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings /// @param _userAddress - address of user /// @param _stakingIds - array of staking ids which should be used to estimate max loan amount /// @param _loanPlanId - the loan plan user wishes to take loan. /// @return max loaning amount function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) { uint256 _currentMonth = getCurrentMonth(); //require(_currentMonth >= _atMonth, 'cannot see future stakings'); uint256 userStakingsExaEsAmount; for(uint256 i = 0; i < _stakingIds.length; i++) { if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth) && ( // @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75% stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed || now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100) ) ) { userStakingsExaEsAmount = userStakingsExaEsAmount .add(stakings[_userAddress][_stakingIds[i]].exaEsAmount .mul(loanPlans[_loanPlanId].maxLoanAmountPercent) .div(100) // .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15) // .div(15) ); } } return userStakingsExaEsAmount; //.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100); } /// @notice this function is used to take loan on multiple stakings /// @param _loanPlanId - user can select this plan which defines loan duration and loan interest /// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited /// @param _stakingIds - staking ids user wishes to encash for taking the loan function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public { // @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period uint256 _currentMonth = getCurrentMonth(); uint256 _userStakingsExaEsAmount; for(uint256 i = 0; i < _stakingIds.length; i++) { if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth) && ( // @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75% stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed || now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100) ) ) { // @dev store sum in a number _userStakingsExaEsAmount = _userStakingsExaEsAmount .add( stakings[msg.sender][ _stakingIds[i] ].exaEsAmount .mul(loanPlans[_loanPlanId].maxLoanAmountPercent) .div(100) ); // @dev subtract total active stakings uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth; uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months; for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) { totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount); } // @dev make stakings inactive for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) { stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true; stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan } } } uint256 _maxLoaningAmount = _userStakingsExaEsAmount; if(_exaEsAmount > _maxLoaningAmount) { require(false // , 'cannot loan more than maxLoaningAmount' ); } uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100); uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest); require( token.transfer(address(nrtManager), _loanInterest) ); require( nrtManager.UpdateLuckpool(_loanInterest) ); loans[msg.sender].push(Loan({ exaEsAmount: _exaEsAmount, timestamp: now, loanPlanId: _loanPlanId, status: 1, stakingIds: _stakingIds })); // @dev send user amount require( token.transfer(msg.sender, _loanAmountToTransfer) ); emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1); } /// @notice repay loan functionality /// @dev need to give allowance before this /// @param _loanId - select loan to repay function repayLoanSelf(uint256 _loanId) public { require(loans[msg.sender][_loanId].status == 1 // , 'can only repay pending loans' ); require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now // , 'cannot repay expired loan' ); require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount) // , 'cannot receive enough tokens, please check if allowance is there' ); loans[msg.sender][_loanId].status = 2; // @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) { uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i]; stakings[msg.sender][_stakingId].status = 1; uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth); uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months; for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) { stakings[msg.sender][_stakingId].isMonthClaimed[i] = false; totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount); } } // add repay event emit RepayLoan(msg.sender, _loanId); } function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public { uint256 _amountToBurn; for(uint256 i = 0; i < _addressArray.length; i++) { require( loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1 // , 'loan should not be repayed' ); require( now > loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp + loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth) // , 'loan should have crossed its loan period' ); uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds; /// @dev add staking amounts of all stakings on which loan is taken for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) { _amountToBurn = _amountToBurn.add( stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount ); } /// @dev sub loan amount _amountToBurn = _amountToBurn.sub( loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount ); } require(token.transfer(address(nrtManager), _amountToBurn)); require(nrtManager.UpdateBurnBal(_amountToBurn)); // emit event } /// @notice this function is used to add nominee to a staking /// @param _stakingId - staking id /// @param _nomineeAddress - address of nominee to be added to staking /// @param _shares - amount of shares of the staking to the nominee /// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it. function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public { require(stakings[msg.sender][_stakingId].status == 1 // , 'staking should active' ); require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0 // , 'should not be nominee already' ); stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares); stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares; emit NomineeNew(msg.sender, _stakingId, _nomineeAddress); } /// @notice this function is used to read the nomination of a nominee address of a staking of a user /// @param _userAddress - address of staking owner /// @param _stakingId - staking id /// @param _nomineeAddress - address of nominee /// @return nomination of the nominee function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) { return stakings[_userAddress][_stakingId].nomination[_nomineeAddress]; } // /// @notice this function is used to update nomination of a nominee of sender's staking // /// @param _stakingId - staking id // /// @param _nomineeAddress - address of nominee // /// @param _shares - shares to be updated for the nominee // function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public { // require(stakings[msg.sender][_stakingId].status == 1 // // , 'staking should active' // ); // uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress]; // if(_shares > _oldShares) { // uint256 _diff = _shares.sub(_oldShares); // stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff); // stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff); // } else if(_shares < _oldShares) { // uint256 _diff = _oldShares.sub(_shares); // stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff); // stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff); // } // } /// @notice this function is used to remove nomination of a address /// @param _stakingId - staking id /// @param _nomineeAddress - address of nominee function removeNominee(uint256 _stakingId, address _nomineeAddress) public { require(stakings[msg.sender][_stakingId].status == 1, 'staking should active'); uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender]; stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0; stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares); } /// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking /// @param _userAddress - address of user /// @param _stakingId - staking id function nomineeWithdraw(address _userAddress, uint256 _stakingId) public { // end time stamp > 0 uint256 currentTime = now; require( currentTime > (stakings[_userAddress][_stakingId].timestamp + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth + 12 * earthSecondsInMonth ) // , 'cannot nominee withdraw before ' ); uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender]; require(_nomineeShares > 0 // , 'Not a nominee of this staking' ); //uint256 _totalShares = ; // set staking to nomination mode if it isn't. if(stakings[_userAddress][_stakingId].status != 5) { stakings[_userAddress][_stakingId].status = 5; } // adding principal account uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount; uint256 _pendingAccruedAmountInStaking; // uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth); uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months; // adding monthly benefits which are not claimed for( uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth; i < _stakeEndMonth; i++ ) { if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) { uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount .mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15) .div(15); uint256 _monthlyBenefit = _effectiveAmount .mul(timeAllyMonthlyNRT[i]) .div(totalActiveStakings[i]); _pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2)); _pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2)); } } // now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking // on which user's share will be calculated and sent // marking nominee as claimed by removing his shares stakings[_userAddress][_stakingId].nomination[msg.sender] = 0; uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking .mul(_nomineeShares) .div(stakings[_userAddress][_stakingId].totalNominationShares); token.transfer(msg.sender, _nomineeLiquidShare); uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking .mul(_nomineeShares) .div(stakings[_userAddress][_stakingId].totalNominationShares); launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare); // emit a event emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare); } } pragma solidity ^0.5.2; import "./ERC20Capped.sol"; import "./ERC20Burnable.sol"; import "./ERC20Detailed.sol"; import "./ERC20Pausable.sol"; contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable { event NRTManagerAdded(address NRTManager); constructor() public ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) { mint(msg.sender, 910000000000000000000000000); } int256 public timeMachineDepth; // gives the time machine time function mou() public view returns(uint256) { if(timeMachineDepth < 0) { return now - uint256(timeMachineDepth); } else { return now + uint256(timeMachineDepth); } } // sets the time machine depth function setTimeMachineDepth(int256 _timeMachineDepth) public { timeMachineDepth = _timeMachineDepth; } function goToFuture(uint256 _seconds) public { timeMachineDepth += int256(_seconds); } function goToPast(uint256 _seconds) public { timeMachineDepth -= int256(_seconds); } /** * @dev Function to add NRT Manager to have minting rights * It will transfer the minting rights to NRTManager and revokes it from existing minter * @param NRTManager Address of NRT Manager C ontract */ function AddNRTManager(address NRTManager) public onlyMinter returns (bool) { addMinter(NRTManager); addPauser(NRTManager); renounceMinter(); renouncePauser(); emit NRTManagerAdded(NRTManager); return true; } } pragma solidity ^0.5.2; import "./IERC20.sol"; import "./SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @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 Transfer token to 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) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } pragma solidity ^0.5.2; import "./ERC20.sol"; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } pragma solidity ^0.5.2; import "./ERC20Mintable.sol"; /** * @title Capped token * @dev Mintable token with a token cap. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; constructor (uint256 cap) public { require(cap > 0); _cap = cap; } /** * @return the cap for the token minting. */ function cap() public view returns (uint256) { return _cap; } function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap); super._mint(account, value); } } pragma solidity ^0.5.2; import "./IERC20.sol"; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.2; import "./ERC20.sol"; import "./MinterRole.sol"; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } pragma solidity ^0.5.2; import "./ERC20.sol"; import "./Pausable.sol"; /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.2; import "./Roles.sol"; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity ^0.5.2; import "./Eraswap.sol"; import "./TimeAlly.sol"; contract NRTManager { using SafeMath for uint256; uint256 public lastNRTRelease; // variable to store last release date uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released uint256 public monthCount; // variable to store the count of months from the intial date uint256 public luckPoolBal; // Luckpool Balance uint256 public burnTokenBal; // tokens to be burned Eraswap token; address Owner; //Eraswap public eraswapToken; // different pool address address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607; address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c; address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E; address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88; address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167; address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9; address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657; address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers address public timeAlly; //address of timeAlly Contract uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address; uint256 public platformMaintenanceBal; // variable to store last NRT released to the address; uint256 public marketingAndRNRBal; // variable to store last NRT released to the address; uint256 public kmPardsBal; // variable to store last NRT released to the address; uint256 public contingencyFundsBal; // variable to store last NRT released to the address; uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address; uint256 public powerTokenNRT; // variable to store last NRT released to the address; uint256 public timeAllyNRT; // variable to store last NRT released to the address; uint256 public timeSwappersNRT; // variable to store last NRT released to the address; // Event to watch NRT distribution // @param NRTReleased The amount of NRT released in the month event NRTDistributed(uint256 NRTReleased); /** * Event to watch Transfer of NRT to different Pool * @param pool - The pool name * @param sendAddress - The address of pool * @param value - The value of NRT released **/ event NRTTransfer(string pool, address sendAddress, uint256 value); // Event to watch Tokens Burned // @param amount The amount burned event TokensBurned(uint256 amount); /** * Event to watch the addition of pool address * @param pool - The pool name * @param sendAddress - The address of pool **/ event PoolAddressAdded(string pool, address sendAddress); // Event to watch LuckPool Updation // @param luckPoolBal The current luckPoolBal event LuckPoolUpdated(uint256 luckPoolBal); // Event to watch BurnTokenBal Updation // @param burnTokenBal The current burnTokenBal event BurnTokenBalUpdated(uint256 burnTokenBal); /** * @dev Throws if caller is not timeAlly */ modifier OnlyAllowed() { require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised"); _; } /** * @dev Throws if caller is not owner */ modifier OnlyOwner() { require(msg.sender == Owner,"Only Owner is authorised"); _; } /** * @dev Should burn tokens according to the total circulation * @return true if success */ function burnTokens() internal returns (bool){ if(burnTokenBal == 0){ return true; } else{ uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month if(MaxAmount >= burnTokenBal ){ token.burn(burnTokenBal); burnTokenBal = 0; } else{ burnTokenBal = burnTokenBal.sub(MaxAmount); token.burn(MaxAmount); } return true; } } /** * @dev To update pool addresses * @param pool - A List of pool addresses * Updates if pool address is not already set and if given address is not zero * @return true if success */ function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){ if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){ newTalentsAndPartnerships = pool[0]; emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships); } if((pool[1] != address(0)) && (platformMaintenance == address(0))){ platformMaintenance = pool[1]; emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance); } if((pool[2] != address(0)) && (marketingAndRNR == address(0))){ marketingAndRNR = pool[2]; emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR); } if((pool[3] != address(0)) && (kmPards == address(0))){ kmPards = pool[3]; emit PoolAddressAdded( "KmPards", kmPards); } if((pool[4] != address(0)) && (contingencyFunds == address(0))){ contingencyFunds = pool[4]; emit PoolAddressAdded( "ContingencyFunds", contingencyFunds); } if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){ researchAndDevelopment = pool[5]; emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment); } if((pool[6] != address(0)) && (powerToken == address(0))){ powerToken = pool[6]; emit PoolAddressAdded( "PowerToken", powerToken); } if((pool[7] != address(0)) && (timeSwappers == address(0))){ timeSwappers = pool[7]; emit PoolAddressAdded( "TimeSwapper", timeSwappers); } if((pool[8] != address(0)) && (timeAlly == address(0))){ timeAlly = pool[8]; emit PoolAddressAdded( "TimeAlly", timeAlly); } return true; } /** * @dev Function to update luckpool balance * @param amount Amount to be updated */ function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){ luckPoolBal = luckPoolBal.add(amount); emit LuckPoolUpdated(luckPoolBal); return true; } /** * @dev Function to trigger to update for burning of tokens * @param amount Amount to be updated */ function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){ burnTokenBal = burnTokenBal.add(amount); emit BurnTokenBalUpdated(burnTokenBal); return true; } /** * @dev To invoke monthly release * @return true if success */ function MonthlyNRTRelease() external returns (bool) { require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month"); uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available. // Calculating NRT to be released to each of the pools newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100); platformMaintenanceBal = (NRTBal.mul(10)).div(100); marketingAndRNRBal = (NRTBal.mul(10)).div(100); kmPardsBal = (NRTBal.mul(10)).div(100); contingencyFundsBal = (NRTBal.mul(10)).div(100); researchAndDevelopmentBal = (NRTBal.mul(5)).div(100); powerTokenNRT = (NRTBal.mul(10)).div(100); timeAllyNRT = (NRTBal.mul(15)).div(100); timeSwappersNRT = (NRTBal.mul(25)).div(100); // sending tokens to respective wallets and emitting events token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal); emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal); token.mint(platformMaintenance,platformMaintenanceBal); emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal); token.mint(marketingAndRNR,marketingAndRNRBal); emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal); token.mint(kmPards,kmPardsBal); emit NRTTransfer("kmPards", kmPards, kmPardsBal); token.mint(contingencyFunds,contingencyFundsBal); emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal); token.mint(researchAndDevelopment,researchAndDevelopmentBal); emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal); token.mint(powerToken,powerTokenNRT); emit NRTTransfer("powerToken", powerToken, powerTokenNRT); token.mint(timeAlly,timeAllyNRT); TimeAlly timeAllyContract = TimeAlly(timeAlly); timeAllyContract.increaseMonth(timeAllyNRT); emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT); token.mint(timeSwappers,timeSwappersNRT); emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT); // Reseting NRT emit NRTDistributed(NRTBal); luckPoolBal = 0; lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days burnTokens(); // burning burnTokenBal emit TokensBurned(burnTokenBal); if(monthCount == 11){ monthCount = 0; annualNRTAmount = (annualNRTAmount.mul(90)).div(100); monthlyNRTAmount = annualNRTAmount.div(12); } else{ monthCount = monthCount.add(1); } return true; } /** * @dev Constructor */ constructor(address eraswaptoken) public{ token = Eraswap(eraswaptoken); lastNRTRelease = now; annualNRTAmount = 819000000000000000000000000; monthlyNRTAmount = annualNRTAmount.div(uint256(12)); monthCount = 0; Owner = msg.sender; } } pragma solidity ^0.5.2; import "./PauserRole.sol"; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @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 onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } pragma solidity ^0.5.2; import "./Roles.sol"; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @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; } /** * @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 unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.5.10; import './SafeMath.sol'; import './Eraswap.sol'; import './NRTManager.sol'; /* Potential bugs: this contract is designed assuming NRT Release will happen every month. There might be issues when the NRT scheduled - added stakingMonth property in Staking struct fix withdraw fractionFrom15 luck pool - done add loanactive contition to take loan - done ensure stakingMonth in the struct is being used every where instead of calculation - done remove local variables uncesessary final the earthSecondsInMonth amount in TimeAlly as well in NRT add events for required functions */ /// @author The EraSwap Team /// @title TimeAlly Smart Contract /// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee contract TimeAlly { using SafeMath for uint256; struct Staking { uint256 exaEsAmount; uint256 timestamp; uint256 stakingMonth; uint256 stakingPlanId; uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode uint256 loanId; uint256 totalNominationShares; mapping (uint256 => bool) isMonthClaimed; mapping (address => uint256) nomination; } struct StakingPlan { uint256 months; uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT // bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan. bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months } struct Loan { uint256 exaEsAmount; uint256 timestamp; uint256 loanPlanId; uint256 status; // @dev 1 => not repayed yet; 2 => repayed uint256[] stakingIds; } struct LoanPlan { uint256 loanMonths; uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan } uint256 public deployedTimestamp; address public owner; Eraswap public token; NRTManager public nrtManager; /// @dev 1 Year = 365.242 days for taking care of leap years uint256 public earthSecondsInMonth = 2629744; // uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year StakingPlan[] public stakingPlans; LoanPlan[] public loanPlans; // user activity details: mapping(address => Staking[]) public stakings; mapping(address => Loan[]) public loans; mapping(address => uint256) public launchReward; /// @dev TimeAlly month to exaEsAmount mapping. mapping (uint256 => uint256) public totalActiveStakings; /// @notice NRT being received from NRT Manager every month is stored in this array /// @dev current month is the length of this array uint256[] public timeAllyMonthlyNRT; event NewStaking ( address indexed _userAddress, uint256 indexed _stakePlanId, uint256 _exaEsAmount, uint256 _stakingId ); event PrincipalWithdrawl ( address indexed _userAddress, uint256 _stakingId ); event NomineeNew ( address indexed _userAddress, uint256 indexed _stakingId, address indexed _nomineeAddress ); event NomineeWithdraw ( address indexed _userAddress, uint256 indexed _stakingId, address indexed _nomineeAddress, uint256 _liquid, uint256 _accrued ); event BenefitWithdrawl ( address indexed _userAddress, uint256 _stakingId, uint256[] _months, uint256 _halfBenefit ); event NewLoan ( address indexed _userAddress, uint256 indexed _loanPlanId, uint256 _exaEsAmount, uint256 _loanInterest, uint256 _loanId ); event RepayLoan ( address indexed _userAddress, uint256 _loanId ); modifier onlyNRTManager() { require( msg.sender == address(nrtManager) // , 'only NRT manager can call' ); _; } modifier onlyOwner() { require( msg.sender == owner // , 'only deployer can call' ); _; } /// @notice sets up TimeAlly contract when deployed /// @param _tokenAddress - is EraSwap contract address /// @param _nrtAddress - is NRT Manager contract address constructor(address _tokenAddress, address _nrtAddress) public { owner = msg.sender; token = Eraswap(_tokenAddress); nrtManager = NRTManager(_nrtAddress); deployedTimestamp = now; timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released } /// @notice this function is used by NRT manager to communicate NRT release to TimeAlly function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager { timeAllyMonthlyNRT.push(_timeAllyNRT); } /// @notice TimeAlly month is dependent on the monthly NRT release /// @return current month is the TimeAlly month function getCurrentMonth() public view returns (uint256) { return timeAllyMonthlyNRT.length - 1; } /// @notice this function is used by owner to create plans for new stakings /// @param _months - is number of staking months of a plan. for eg. 12 months /// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool /// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner { stakingPlans.push(StakingPlan({ months: _months, fractionFrom15: _fractionFrom15, // isPlanActive: true, isUrgentLoanAllowed: _isUrgentLoanAllowed })); } /// @notice this function is used by owner to create plans for new loans /// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period /// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner { require(_maxLoanAmountPercent <= 100 // , 'everyone should not be able to take loan more than 100 percent of their stakings' ); loanPlans.push(LoanPlan({ loanMonths: _loanMonths, loanRate: _loanRate, maxLoanAmountPercent: _maxLoanAmountPercent })); } /// @notice takes ES from user and locks it for a time according to plan selected by user /// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake /// @param _stakingPlanId - plan for staking function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public { /// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase require(_exaEsAmount > 0 // , 'staking amount should be non zero' ); require(token.transferFrom(msg.sender, address(this), _exaEsAmount) // , 'could not transfer tokens' ); uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months; // @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs for( uint256 month = getCurrentMonth() + 1; month <= stakeEndMonth; month++ ) { totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount); } stakings[msg.sender].push(Staking({ exaEsAmount: _exaEsAmount, timestamp: now, stakingMonth: getCurrentMonth(), stakingPlanId: _stakingPlanId, status: 1, loanId: 0, totalNominationShares: 0 })); emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1); } /// @notice this function is used to see total stakings of any user of TimeAlly /// @param _userAddress - address of user /// @return number of stakings of _userAddress function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) { return stakings[_userAddress].length; } /// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking. /// @dev Allowance is required before topup. /// @param _exaEsAmount - amount to add to your rewards for sending rewards to others function topupRewardBucket(uint256 _exaEsAmount) public { require(token.transferFrom(msg.sender, address(this), _exaEsAmount)); launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount); } /// @notice this function is used to send rewards to multiple users /// @param _addresses - array of address to send rewards /// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner { for(uint256 i = 0; i < _addresses.length; i++) { launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]); launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]); } } /// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards /// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings function claimLaunchReward(uint256 _stakingPlanId) public { // require(stakingPlans[_stakingPlanId].isPlanActive // // , 'selected plan is not active' // ); require(launchReward[msg.sender] > 0 // , 'launch reward should be non zero' ); uint256 reward = launchReward[msg.sender]; launchReward[msg.sender] = 0; // @dev logic similar to newStaking function uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months; // @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs for( uint256 month = getCurrentMonth() + 1; month <= stakeEndMonth; month++ ) { totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option } stakings[msg.sender].push(Staking({ exaEsAmount: reward, timestamp: now, stakingMonth: getCurrentMonth(), stakingPlanId: _stakingPlanId, status: 1, loanId: 0, totalNominationShares: 0 })); emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1); } /// @notice used internally to see if staking is active or not. does not include if staking is claimed. /// @param _userAddress - address of user /// @param _stakingId - staking id /// @param _atMonth - particular month to check staking active /// @return true is staking is in correct time frame and also no loan on it function isStakingActive( address _userAddress, uint256 _stakingId, uint256 _atMonth ) public view returns (bool) { //uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth); return ( /// @dev _atMonth should be a month after which staking starts stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth /// @dev _atMonth should be a month before which staking ends && stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth /// @dev staking should have active status && stakings[_userAddress][_stakingId].status == 1 /// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking && ( getCurrentMonth() != _atMonth || now >= stakings[_userAddress][_stakingId].timestamp .add( getCurrentMonth() .sub(stakings[_userAddress][_stakingId].stakingMonth) .mul(earthSecondsInMonth) ) ) ); } /// @notice this function is used for seeing the benefits of a staking of any user /// @param _userAddress - address of user /// @param _stakingId - staking id /// @param _months - array of months user is interested to see benefits. /// @return amount of ExaES of benefits of entered months function seeBenefitOfAStakingByMonths( address _userAddress, uint256 _stakingId, uint256[] memory _months ) public view returns (uint256) { uint256 benefitOfAllMonths; for(uint256 i = 0; i < _months.length; i++) { /// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function. // require( // isStakingActive(_userAddress, _stakingId, _months[i]) // && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]] // // , 'staking must be active' // ); if(isStakingActive(_userAddress, _stakingId, _months[i]) && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) { uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount .mul(timeAllyMonthlyNRT[ _months[i] ]) .div(totalActiveStakings[ _months[i] ]); benefitOfAllMonths = benefitOfAllMonths.add(benefit); } } return benefitOfAllMonths.mul( stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15 ).div(15); } /// @notice this function is used for withdrawing the benefits of a staking of any user /// @param _stakingId - staking id /// @param _months - array of months user is interested to withdraw benefits of staking. function withdrawBenefitOfAStakingByMonths( uint256 _stakingId, uint256[] memory _months ) public { uint256 _benefitOfAllMonths; for(uint256 i = 0; i < _months.length; i++) { // require( // isStakingActive(msg.sender, _stakingId, _months[i]) // && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] // // , 'staking must be active' // ); if(isStakingActive(msg.sender, _stakingId, _months[i]) && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) { uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount .mul(timeAllyMonthlyNRT[ _months[i] ]) .div(totalActiveStakings[ _months[i] ]); _benefitOfAllMonths = _benefitOfAllMonths.add(_benefit); stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true; } } uint256 _luckPool = _benefitOfAllMonths .mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) ) .div( 15 ); require( token.transfer(address(nrtManager), _luckPool) ); require( nrtManager.UpdateLuckpool(_luckPool) ); _benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool); uint256 _halfBenefit = _benefitOfAllMonths.div(2); require( token.transfer(msg.sender, _halfBenefit) ); launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit); // emit event emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit); } /// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed /// @param _stakingIds - input which stakings to withdraw function withdrawExpiredStakings(uint256[] memory _stakingIds) public { for(uint256 i = 0; i < _stakingIds.length; i++) { require(now >= stakings[msg.sender][_stakingIds[i]].timestamp .add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth)) // , 'cannot withdraw before staking ends' ); stakings[msg.sender][_stakingIds[i]].status = 3; token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount); emit PrincipalWithdrawl(msg.sender, _stakingIds[i]); } } /// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings /// @param _userAddress - address of user /// @param _stakingIds - array of staking ids which should be used to estimate max loan amount /// @param _loanPlanId - the loan plan user wishes to take loan. /// @return max loaning amount function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) { uint256 _currentMonth = getCurrentMonth(); //require(_currentMonth >= _atMonth, 'cannot see future stakings'); uint256 userStakingsExaEsAmount; for(uint256 i = 0; i < _stakingIds.length; i++) { if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth) && ( // @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75% stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed || now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100) ) ) { userStakingsExaEsAmount = userStakingsExaEsAmount .add(stakings[_userAddress][_stakingIds[i]].exaEsAmount .mul(loanPlans[_loanPlanId].maxLoanAmountPercent) .div(100) // .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15) // .div(15) ); } } return userStakingsExaEsAmount; //.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100); } /// @notice this function is used to take loan on multiple stakings /// @param _loanPlanId - user can select this plan which defines loan duration and loan interest /// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited /// @param _stakingIds - staking ids user wishes to encash for taking the loan function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public { // @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period uint256 _currentMonth = getCurrentMonth(); uint256 _userStakingsExaEsAmount; for(uint256 i = 0; i < _stakingIds.length; i++) { if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth) && ( // @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75% stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed || now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100) ) ) { // @dev store sum in a number _userStakingsExaEsAmount = _userStakingsExaEsAmount .add( stakings[msg.sender][ _stakingIds[i] ].exaEsAmount .mul(loanPlans[_loanPlanId].maxLoanAmountPercent) .div(100) ); // @dev subtract total active stakings uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth; uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months; for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) { totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount); } // @dev make stakings inactive for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) { stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true; stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan } } } uint256 _maxLoaningAmount = _userStakingsExaEsAmount; if(_exaEsAmount > _maxLoaningAmount) { require(false // , 'cannot loan more than maxLoaningAmount' ); } uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100); uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest); require( token.transfer(address(nrtManager), _loanInterest) ); require( nrtManager.UpdateLuckpool(_loanInterest) ); loans[msg.sender].push(Loan({ exaEsAmount: _exaEsAmount, timestamp: now, loanPlanId: _loanPlanId, status: 1, stakingIds: _stakingIds })); // @dev send user amount require( token.transfer(msg.sender, _loanAmountToTransfer) ); emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1); } /// @notice repay loan functionality /// @dev need to give allowance before this /// @param _loanId - select loan to repay function repayLoanSelf(uint256 _loanId) public { require(loans[msg.sender][_loanId].status == 1 // , 'can only repay pending loans' ); require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now // , 'cannot repay expired loan' ); require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount) // , 'cannot receive enough tokens, please check if allowance is there' ); loans[msg.sender][_loanId].status = 2; // @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) { uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i]; stakings[msg.sender][_stakingId].status = 1; uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth); uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months; for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) { stakings[msg.sender][_stakingId].isMonthClaimed[i] = false; totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount); } } // add repay event emit RepayLoan(msg.sender, _loanId); } function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public { uint256 _amountToBurn; for(uint256 i = 0; i < _addressArray.length; i++) { require( loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1 // , 'loan should not be repayed' ); require( now > loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp + loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth) // , 'loan should have crossed its loan period' ); uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds; /// @dev add staking amounts of all stakings on which loan is taken for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) { _amountToBurn = _amountToBurn.add( stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount ); } /// @dev sub loan amount _amountToBurn = _amountToBurn.sub( loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount ); } require(token.transfer(address(nrtManager), _amountToBurn)); require(nrtManager.UpdateBurnBal(_amountToBurn)); // emit event } /// @notice this function is used to add nominee to a staking /// @param _stakingId - staking id /// @param _nomineeAddress - address of nominee to be added to staking /// @param _shares - amount of shares of the staking to the nominee /// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it. function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public { require(stakings[msg.sender][_stakingId].status == 1 // , 'staking should active' ); require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0 // , 'should not be nominee already' ); stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares); stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares; emit NomineeNew(msg.sender, _stakingId, _nomineeAddress); } /// @notice this function is used to read the nomination of a nominee address of a staking of a user /// @param _userAddress - address of staking owner /// @param _stakingId - staking id /// @param _nomineeAddress - address of nominee /// @return nomination of the nominee function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) { return stakings[_userAddress][_stakingId].nomination[_nomineeAddress]; } // /// @notice this function is used to update nomination of a nominee of sender's staking // /// @param _stakingId - staking id // /// @param _nomineeAddress - address of nominee // /// @param _shares - shares to be updated for the nominee // function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public { // require(stakings[msg.sender][_stakingId].status == 1 // // , 'staking should active' // ); // uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress]; // if(_shares > _oldShares) { // uint256 _diff = _shares.sub(_oldShares); // stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff); // stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff); // } else if(_shares < _oldShares) { // uint256 _diff = _oldShares.sub(_shares); // stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff); // stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff); // } // } /// @notice this function is used to remove nomination of a address /// @param _stakingId - staking id /// @param _nomineeAddress - address of nominee function removeNominee(uint256 _stakingId, address _nomineeAddress) public { require(stakings[msg.sender][_stakingId].status == 1, 'staking should active'); uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender]; stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0; stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares); } /// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking /// @param _userAddress - address of user /// @param _stakingId - staking id function nomineeWithdraw(address _userAddress, uint256 _stakingId) public { // end time stamp > 0 uint256 currentTime = now; require( currentTime > (stakings[_userAddress][_stakingId].timestamp + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth + 12 * earthSecondsInMonth ) // , 'cannot nominee withdraw before ' ); uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender]; require(_nomineeShares > 0 // , 'Not a nominee of this staking' ); //uint256 _totalShares = ; // set staking to nomination mode if it isn't. if(stakings[_userAddress][_stakingId].status != 5) { stakings[_userAddress][_stakingId].status = 5; } // adding principal account uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount; uint256 _pendingAccruedAmountInStaking; // uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth); uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months; // adding monthly benefits which are not claimed for( uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth; i < _stakeEndMonth; i++ ) { if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) { uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount .mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15) .div(15); uint256 _monthlyBenefit = _effectiveAmount .mul(timeAllyMonthlyNRT[i]) .div(totalActiveStakings[i]); _pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2)); _pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2)); } } // now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking // on which user's share will be calculated and sent // marking nominee as claimed by removing his shares stakings[_userAddress][_stakingId].nomination[msg.sender] = 0; uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking .mul(_nomineeShares) .div(stakings[_userAddress][_stakingId].totalNominationShares); token.transfer(msg.sender, _nomineeLiquidShare); uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking .mul(_nomineeShares) .div(stakings[_userAddress][_stakingId].totalNominationShares); launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare); // emit a event emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare); } }
tokens to be burned
uint256 public burnTokenBal;
12,590,509
[ 1, 7860, 358, 506, 18305, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 18305, 1345, 38, 287, 31, 1171, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x89737528A1e4eff137563cF5d4D2453199B17d3E/sources/EasyBid.sol
require that sender has at least 1 Nyan-2approve swap allowancerequire that expected eth value of tokens is higher than profitlossor the caller should be msg.senderreduce expected output by 2%in profit?in losses?if call is in profit,send 30% to biddersend 10% to the callersend the remainder to the Nyan Fundincrease eth profitsif in profit and lost LP exists, give back LP equal to profits sent to fund(soon)or losses on bidderreduce bidder LP by amount
function callBid( address _bidder, uint112 index ) public delegatedOnly { require(ERC20(nyanV2).balanceOf(msg.sender) > 1 ether); ERC20(bid[_bidder].token).approve(uniswapRouter, ERC20(bid[_bidder].token).totalSupply()); address[] memory path = new address[](2); path[0] = bid[_bidder].token; path[1] = IUniswapV2Router02(uniswapRouter).WETH(); uint[] memory expectedOutputs = IUniswapV2Router02(uniswapRouter).getAmountsOut( bid[_bidder].tokenAmount, path ); uint256 slippage = expectedOutputs[expectedOutputs.length-1].mul(200).div(10000); uint[] memory amounts = IUniswapV2Router02(uniswapRouter).swapExactTokensForETH( bid[_bidder].tokenAmount, expectedOutputs[expectedOutputs.length-1].sub(slippage), path, address(this), now + 2 days ); uint256 profits; if (bid[_bidder].ethUsed < amounts[amounts.length - 1]) { profits = amounts[amounts.length - 1].sub(bid[_bidder].ethUsed); } if (_bidder != msg.sender) { if (expectedOutputs[expectedOutputs.length-1] > bid[_bidder].ethUsed) { require(isInProfit(expectedOutputs, _bidder)); } if (expectedOutputs[expectedOutputs.length-1] < bid[_bidder].ethUsed) { require(isInProfit(expectedOutputs, _bidder)); } } if (profits > 100) { } if (amounts[amounts.length - 1] >= bid[_bidder].ethUsed) { bidder[_bidder].ethProfits = bidder[_bidder].ethProfits.add(amounts[amounts.length - 1]); fundProfitsGenerated = fundProfitsGenerated.add(amounts[amounts.length - 1].mul(6000).div(10000)); } if (amounts[amounts.length - 1] < bid[_bidder].ethUsed) { uint256 percentageReduction = uint32(100).sub( bid[_bidder].ethUsed .mul(100) .div(expectedOutputs[expectedOutputs.length-1]) ); uint256 losses = percentageReduction.mul(NyanV2(nyanV2).getStakedNyanV2LP(_bidder)).div(100); NyanV2(nyanV2).reduceLPAmount(_bidder, losses); bidder[_bidder].ethLosses = bidder[_bidder].ethLosses.add(losses); } bidder[msg.sender].hasLiveBid = false; emit CallMade(_bidder, amounts[amounts.length - 1]); }
15,688,352
[ 1, 6528, 716, 5793, 711, 622, 4520, 404, 423, 93, 304, 17, 22, 12908, 537, 7720, 1699, 19292, 822, 1039, 716, 2665, 13750, 460, 434, 2430, 353, 10478, 2353, 450, 7216, 7873, 280, 326, 4894, 1410, 506, 1234, 18, 15330, 12498, 2665, 876, 635, 576, 9, 267, 450, 7216, 35, 267, 24528, 35, 430, 745, 353, 316, 450, 7216, 16, 4661, 5196, 9, 358, 324, 1873, 414, 409, 1728, 9, 358, 326, 19932, 409, 326, 10022, 358, 326, 423, 93, 304, 478, 1074, 267, 11908, 13750, 9214, 1282, 430, 316, 450, 7216, 471, 13557, 511, 52, 1704, 16, 8492, 1473, 511, 52, 3959, 358, 9214, 1282, 3271, 358, 284, 1074, 12, 2048, 265, 13, 280, 24528, 603, 9949, 765, 12498, 9949, 765, 511, 52, 635, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 745, 17763, 12, 203, 3639, 1758, 389, 19773, 765, 16, 203, 3639, 2254, 17666, 770, 203, 565, 262, 1071, 30055, 3386, 288, 203, 3639, 2583, 12, 654, 39, 3462, 12, 18538, 304, 58, 22, 2934, 12296, 951, 12, 3576, 18, 15330, 13, 405, 404, 225, 2437, 1769, 203, 3639, 4232, 39, 3462, 12, 19773, 63, 67, 19773, 765, 8009, 2316, 2934, 12908, 537, 12, 318, 291, 91, 438, 8259, 16, 4232, 39, 3462, 12, 19773, 63, 67, 19773, 765, 8009, 2316, 2934, 4963, 3088, 1283, 10663, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 9949, 63, 67, 19773, 765, 8009, 2316, 31, 203, 3639, 589, 63, 21, 65, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 318, 291, 91, 438, 8259, 2934, 59, 1584, 44, 5621, 203, 3639, 2254, 8526, 3778, 2665, 13856, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 318, 291, 91, 438, 8259, 2934, 588, 6275, 87, 1182, 12, 203, 5411, 9949, 63, 67, 19773, 765, 8009, 2316, 6275, 16, 7010, 5411, 589, 203, 3639, 11272, 203, 3639, 2254, 5034, 272, 3169, 2433, 273, 2665, 13856, 63, 3825, 13856, 18, 2469, 17, 21, 8009, 16411, 12, 6976, 2934, 2892, 12, 23899, 1769, 203, 3639, 2254, 8526, 3778, 30980, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 318, 291, 91, 438, 8259, 2934, 22270, 14332, 5157, 1290, 1584, 44, 12, 203, 5411, 9949, 63, 67, 19773, 765, 8009, 2316, 2 ]
pragma solidity ^0.8.3; // SPDX-License-Identifier: Unlicensed /** * @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); } // 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /* * @dev 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; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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 () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @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; } } 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; } // contract implementation contract BabyYachtClub is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint8 private _decimals = 9; // string private _name = "BabyYachtClub"; // name string private _symbol = "BYacht"; // symbol uint256 private _tTotal = 1000 * 10**9 * 10**uint256(_decimals); // total supply // % to holders uint256 public defaultTaxFee = 2; uint256 public _taxFee = defaultTaxFee; uint256 private _previousTaxFee = _taxFee; // % to swap & send to marketing wallet uint256 public defaultMarketingFee = 4; uint256 public _marketingFee = defaultMarketingFee; uint256 private _previousMarketingFee = _marketingFee; uint256 public _marketingFee4Sellers = 8; bool public feesOnSellersAndBuyers = true; uint256 public _maxTxAmount = _tTotal.div(1).div(100); uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100); address payable public marketingWallet = payable(0x5f49cb4284DDB68F398a5f1ce2927eD01c773622); // Wallet // mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tFeeTotal; uint256 private _rTotal = (MAX - (MAX % _tTotal)); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndSend; bool public SwapAndSendEnabled = true; event SwapAndSendEnabledUpdated(bool enabled); modifier lockTheSwap { inSwapAndSend = true; _; inSwapAndSend = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function removeAllFee() private { if(_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; } //to recieve ETH receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div( 10**2 ); } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + send lock? // also, don't get caught in a circular sending event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function setFees(address recipient) private { _taxFee = defaultTaxFee; _marketingFee = defaultMarketingFee; if (recipient == uniswapV2Pair) { // sell _marketingFee = _marketingFee4Sellers; } } function SwapAndSend(uint256 contractTokenBalance) private lockTheSwap { // 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), contractTokenBalance); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( contractTokenBalance, 0, // accept any amount of ETH path, address(this), block.timestamp ); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { marketingWallet.transfer(contractETHBalance); } } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function setDefaultMarketingFee(uint256 marketingFee) external onlyOwner() { defaultMarketingFee = marketingFee; } function setMarketingFee4Sellers(uint256 marketingFee4Sellers) external onlyOwner() { _marketingFee4Sellers = marketingFee4Sellers; } function setFeesOnSellersAndBuyers(bool _enabled) public onlyOwner() { feesOnSellersAndBuyers = _enabled; } function setSwapAndSendEnabled(bool _enabled) public onlyOwner() { SwapAndSendEnabled = _enabled; emit SwapAndSendEnabledUpdated(_enabled); } function setnumTokensToExchangeForMarketing(uint256 _numTokensToExchangeForMarketing) public onlyOwner() { numTokensToExchangeForMarketing = _numTokensToExchangeForMarketing; } function _setMarketingWallet(address payable wallet) external onlyOwner() { marketingWallet = wallet; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } }
contract implementation % to holders % to swap & send to marketing wallet
contract BabyYachtClub is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint8 private _decimals = 9; uint256 public defaultTaxFee = 2; uint256 public _taxFee = defaultTaxFee; uint256 private _previousTaxFee = _taxFee; uint256 public defaultMarketingFee = 4; uint256 public _marketingFee = defaultMarketingFee; uint256 private _previousMarketingFee = _marketingFee; uint256 public _marketingFee4Sellers = 8; bool public feesOnSellersAndBuyers = true; uint256 public _maxTxAmount = _tTotal.div(1).div(100); uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100); mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tFeeTotal; uint256 private _rTotal = (MAX - (MAX % _tTotal)); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndSend; bool public SwapAndSendEnabled = true; event SwapAndSendEnabledUpdated(bool enabled); modifier lockTheSwap { inSwapAndSend = true; _; inSwapAndSend = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function removeAllFee() private { if(_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; } receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div( 10**2 ); } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } bool takeFee = true; function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from,to,amount,takeFee); } function setFees(address recipient) private { _taxFee = defaultTaxFee; _marketingFee = defaultMarketingFee; _marketingFee = _marketingFee4Sellers; } }
13,709,102
[ 1, 16351, 4471, 738, 358, 366, 4665, 738, 358, 7720, 473, 1366, 358, 13667, 310, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 24383, 61, 497, 88, 2009, 373, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2254, 28, 3238, 389, 31734, 273, 2468, 31, 203, 203, 203, 565, 2254, 5034, 1071, 805, 7731, 14667, 273, 576, 31, 203, 565, 2254, 5034, 1071, 389, 8066, 14667, 273, 805, 7731, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 11515, 7731, 14667, 273, 389, 8066, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 805, 3882, 21747, 14667, 273, 1059, 31, 203, 565, 2254, 5034, 1071, 389, 3355, 21747, 14667, 273, 805, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 11515, 3882, 21747, 14667, 273, 389, 3355, 21747, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 389, 3355, 21747, 14667, 24, 55, 1165, 414, 273, 1725, 31, 203, 203, 565, 1426, 1071, 1656, 281, 1398, 55, 1165, 414, 1876, 38, 9835, 414, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 389, 1896, 4188, 6275, 273, 389, 88, 5269, 18, 2892, 12, 21, 2934, 2892, 12, 6625, 1769, 203, 565, 2254, 5034, 1071, 818, 5157, 774, 11688, 1290, 3882, 21747, 273, 389, 88, 5269, 18, 2892, 12, 6625, 2934, 2892, 12, 6625, 1769, 203, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 2 ]
./full_match/1/0xC96ff67f755b2C0e00456601BBE83760F910D7a0/sources/Inuyasha.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Inuyasha", "DEMON") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), WETH); excludeFromMaxTransaction(address(uniswapV2Pair), true); uint256 _buyDevFee = 1; uint256 _buyLiquidityFee = 2; uint256 _sellDevFee = 1; uint256 _sellLiquidityFee = 2; uint256 totalSupply = 100_000_000_000 * 1e17; buyDevFee = _buyDevFee; buyLiquidityFee = _buyLiquidityFee; buyTotalFees = buyDevFee + buyLiquidityFee; sellDevFee = _sellDevFee; sellLiquidityFee = _sellLiquidityFee; sellTotalFees = sellDevFee + sellLiquidityFee; 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);
16,576,977
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 382, 9835, 961, 69, 3113, 315, 1639, 17667, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 678, 1584, 44, 1769, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 404, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 576, 31, 203, 203, 3639, 2254, 5034, 389, 87, 1165, 8870, 14667, 273, 404, 31, 203, 3639, 2254, 5034, 389, 87, 1165, 48, 18988, 24237, 14667, 273, 576, 31, 203, 203, 3639, 2254, 5034, 2078, 3088, 1283, 273, 2130, 67, 3784, 67, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/access/AccessControl.sol'; import './IWhitelist.sol'; import './TimeContract.sol'; contract PropyAuctionV2 is AccessControl, TimeContract { using SafeERC20 for IERC20; using Address for *; bytes32 public constant CONFIG_ROLE = keccak256('CONFIG_ROLE'); bytes32 public constant FINALIZE_ROLE = keccak256('FINALIZE_ROLE'); uint32 public constant BID_DEADLINE_EXTENSION = 15 minutes; uint32 public constant MAX_AUCTION_LENGTH = 30 days; IWhitelist public immutable whitelist; // Auction ID is constructed as keccak256(abi.encodePacked(address(nft), uint256(nftId), uint32(startDate))) mapping(bytes32 => Auction) internal auctions; mapping(bytes32 => mapping(address => uint)) internal bids; mapping(address => uint) public unclaimed; struct Auction { uint128 minBid; uint32 deadline; uint32 finalizeTimeout; bool finalized; } event TokensRecovered(address token, address to, uint value); event Bid(IERC721 nft, uint nftId, uint32 start, address user, uint value); event Claimed(IERC721 nft, uint nftId, uint32 start, address user, uint value); event Withdrawn(address user, uint value); event Finalized(IERC721 nft, uint nftId, uint32 start, address winner, uint winnerBid); event AuctionAdded(IERC721 nft, uint nftId, uint32 start, uint32 deadline, uint128 minBid, uint32 timeout); event MinBidUpdated(IERC721 nft, uint nftId, uint32 start, uint128 minBid); event DeadlineExtended(IERC721 nft, uint nftId, uint32 start, uint32 deadline); modifier onlyWhitelisted() { require(whitelist.whitelist(_msgSender()), "Auction: User is not whitelisted"); _; } constructor( address _owner, address _configurator, address _finalizer, IWhitelist _whitelist ) { _grantRole(DEFAULT_ADMIN_ROLE, _owner); _grantRole(CONFIG_ROLE, _configurator); _grantRole(FINALIZE_ROLE, _finalizer); whitelist = _whitelist; } function _auctionId(IERC721 _nft, uint _nftId, uint32 _start) internal pure returns(bytes32) { return keccak256(abi.encodePacked(_nft, _nftId, _start)); } function getAuction(IERC721 _nft, uint _nftId, uint32 _start) external view returns(Auction memory) { return auctions[_auctionId(_nft, _nftId, _start)]; } function getBid(IERC721 _nft, uint _nftId, uint32 _start, address _bidder) public view returns(uint) { return bids[_auctionId(_nft, _nftId, _start)][_bidder]; } function bid(IERC721 _nft, uint _nftId, uint32 _start) external payable virtual { _bid(_nft, _nftId, _start, msg.value); } function _bid(IERC721 _nft, uint _nftId, uint32 _start, uint _amount) internal onlyWhitelisted { require(_amount > 0, 'Auction: Zero bid not allowed'); require(passed(_start), 'Auction: Not started yet'); bytes32 id = _auctionId(_nft, _nftId, _start); Auction memory auction = auctions[id]; require(auction.deadline > 0, 'Auction: Not found'); require(notPassed(auction.deadline), 'Auction: Already finished'); if (passed(auction.deadline - BID_DEADLINE_EXTENSION)) { uint32 newDeadline = uint32(block.timestamp) + BID_DEADLINE_EXTENSION; auctions[id].deadline = newDeadline; emit DeadlineExtended(_nft, _nftId, _start, newDeadline); } uint newBid = bids[id][_msgSender()] + _amount; require(newBid >= auction.minBid, 'Auction: Can not bid less than allowed'); bids[id][_msgSender()] = newBid; emit Bid(_nft, _nftId, _start, _msgSender(), newBid); } function addAuction(IERC721 _nft, uint _nftId, uint32 _start, uint32 _deadline, uint128 _minBid, uint32 _finalizeTimeout) external onlyRole(CONFIG_ROLE) { require(_minBid > 0, 'Auction: Invalid min bid'); require(notPassed(_start), 'Auction: Start should be more than current time'); require(_deadline > _start, 'Auction: Deadline should be more than start time'); require(MAX_AUCTION_LENGTH >= _deadline - _start, 'Auction: Auction time is more than max allowed'); bytes32 id = _auctionId(_nft, _nftId, _start); Auction storage auction = auctions[id]; require(auction.deadline == 0, 'Auction: Already added'); auction.minBid = _minBid; auction.deadline = _deadline; auction.finalizeTimeout = _finalizeTimeout; emit AuctionAdded(_nft, _nftId, _start, _deadline, _minBid, _finalizeTimeout); } function updateMinBid(IERC721 _nft, uint _nftId, uint32 _start, uint128 _minBid) external onlyRole(CONFIG_ROLE) { require(_minBid > 0, 'Auction: Invalid min bid'); Auction storage auction = auctions[_auctionId(_nft, _nftId, _start)]; require(auction.deadline > 0, 'Auction: Not found'); auction.minBid = _minBid; emit MinBidUpdated(_nft, _nftId, _start, _minBid); } function updateDeadline(IERC721 _nft, uint _nftId, uint32 _start, uint32 _deadline) external onlyRole(CONFIG_ROLE) { bytes32 id = _auctionId(_nft, _nftId, _start); Auction memory auction = auctions[id]; require(auction.deadline > 0, 'Auction: Not found'); require(_deadline > auction.deadline, 'Auction: New deadline should be more than previous'); require(_deadline - _start <= MAX_AUCTION_LENGTH, 'Auction: Auction time is more than max allowed'); Auction storage auctionUpdate = auctions[id]; auctionUpdate.deadline = _deadline; emit DeadlineExtended(_nft, _nftId, _start, _deadline); } function finalize(IERC721 _nft, uint _nftId, uint32 _start, address payable _treasury, address _winner) external onlyRole(FINALIZE_ROLE) { bytes32 id = _auctionId(_nft, _nftId, _start); Auction memory auction = auctions[id]; require(auction.deadline > 0, 'Auction: Not found'); require(!auction.finalized, 'Auction: Already finalized'); require(passed(auction.deadline), 'Auction: Not finished yet'); require(notPassed(auction.deadline + auction.finalizeTimeout), 'Auction: Finalize expired, auction cancelled'); uint winnerBid = bids[id][_winner]; require(winnerBid > 0, 'Auction: Winner did not bid'); bids[id][_winner] = 0; auctions[id].finalized = true; _nft.safeTransferFrom(_nft.ownerOf(_nftId), _winner, _nftId); _pay(_treasury, winnerBid); emit Finalized(_nft, _nftId, _start, _winner, winnerBid); } function claim(IERC721 _nft, uint _nftId, uint32 _start) external { claimFor(_nft, _nftId, _start, _msgSender()); } function claimFor(IERC721 _nft, uint _nftId, uint32 _start, address _user) public { bytes32 id = _auctionId(_nft, _nftId, _start); Auction memory auction = auctions[id]; require(_isDone(auction), 'Auction: Not done yet'); uint userBid = bids[id][_user]; require(userBid > 0, 'Auction: Nothing to claim'); _claimFor(_nft, _nftId, _start, _user, userBid); } function _claimFor(IERC721 _nft, uint _nftId, uint32 _start, address _user, uint _userBid) internal { bytes32 id = _auctionId(_nft, _nftId, _start); bids[id][_user] = 0; unclaimed[_user] += _userBid; emit Claimed(_nft, _nftId, _start, _user, _userBid); } function withdraw() external { _withdraw(_msgSender()); } function withdrawFor(address _user) external onlyRole(CONFIG_ROLE) { _withdraw(_user); } function _withdraw(address _user) internal { uint toWithdraw = unclaimed[_user]; require(toWithdraw > 0, 'Auction: Nothing to withdraw'); unclaimed[_user] = 0; _pay(_user, toWithdraw); emit Withdrawn(_user, toWithdraw); } function claimAndWithdrawFor(IERC721 _nft, uint _nftId, uint32 _start, address[] calldata _users) external onlyRole(CONFIG_ROLE) { bytes32 id = _auctionId(_nft, _nftId, _start); Auction memory auction = auctions[id]; require(auction.deadline > 0, 'Auction: Not found'); require(_isDone(auction), 'Auction: Not done yet'); for (uint i = 0; i < _users.length; i++) { address _user = _users[i]; uint _userBid = bids[id][_user]; if (_userBid > 0) { _claimFor(_nft, _nftId, _start, _user, _userBid); } if (unclaimed[_user] > 0) { _withdraw(_user); } } } function claimAndWithdraw(IERC721 _nft, uint _nftId, uint32 _start) external { claimFor(_nft, _nftId, _start, _msgSender()); _withdraw(_msgSender()); } function recoverTokens(IERC20 _token, address _destination, uint _amount) public virtual onlyRole(CONFIG_ROLE) { require(_destination != address(0), 'Auction: Zero address not allowed'); _token.safeTransfer(_destination, _amount); emit TokensRecovered(address(_token), _destination, _amount); } function isDone(IERC721 _nft, uint _nftId, uint32 _start) external view returns(bool) { return _isDone(auctions[_auctionId(_nft, _nftId, _start)]); } function _isDone(Auction memory _auction) internal view returns(bool) { return _auction.finalized || passed(_auction.deadline + _auction.finalizeTimeout); } function _pay(address _to, uint _amount) internal virtual { payable(_to).sendValue(_amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IWhitelist { function whitelist(address _user) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; contract TimeContract { function passed(uint _timestamp) internal view returns(bool) { return _timestamp < block.timestamp; } function notPassed(uint _timestamp) internal view returns(bool) { return !passed(_timestamp); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
* @dev Emitted when `tokenId` token is transferred from `from` to `to`./* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token./* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets./* @dev Returns the number of tokens in ``owner``'s account./* @dev Returns the owner of the `tokenId` token. Requirements: - `tokenId` must exist./* @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./* @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./* @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./* @dev Returns the account approved for `tokenId` token. Requirements: - `tokenId` must exist./* @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./* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. See {setApprovalForAll}/* @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./ SPDX-License-Identifier: MIT OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.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 function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; } pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; ) 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 { 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)); } } 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)); } } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
13,598,557
[ 1, 1514, 11541, 1347, 1375, 2316, 548, 68, 1147, 353, 906, 4193, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 19, 225, 512, 7948, 1347, 1375, 8443, 68, 19808, 1375, 25990, 68, 358, 10680, 326, 1375, 2316, 548, 68, 1147, 18, 19, 225, 512, 7948, 1347, 1375, 8443, 68, 19808, 578, 24960, 21863, 25990, 24065, 1375, 9497, 68, 358, 10680, 777, 434, 2097, 7176, 18, 19, 225, 2860, 326, 1300, 434, 2430, 316, 12176, 8443, 10335, 11, 87, 2236, 18, 19, 225, 2860, 326, 3410, 434, 326, 1375, 2316, 548, 68, 1147, 18, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 1005, 18, 19, 225, 348, 1727, 2357, 29375, 1375, 2316, 548, 68, 1147, 628, 1375, 2080, 68, 358, 1375, 869, 9191, 6728, 1122, 716, 6835, 12045, 854, 18999, 434, 326, 4232, 39, 27, 5340, 1771, 358, 5309, 2430, 628, 3832, 21238, 8586, 18, 29076, 30, 300, 1375, 2080, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 12083, 14060, 654, 39, 3462, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 445, 4183, 5912, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 315, 16644, 5471, 19, 474, 26362, 19, 45, 654, 39, 28275, 18, 18281, 14432, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 315, 6216, 45, 654, 39, 3462, 18, 18281, 14432, 203, 5666, 315, 16644, 6216, 5471, 19, 1887, 18, 18281, 14432, 203, 203, 565, 262, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 24126, 18, 3015, 1190, 4320, 12, 2316, 18, 13866, 18, 9663, 16, 358, 16, 460, 10019, 203, 565, 289, 203, 203, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 467, 654, 39, 3462, 1147, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 288, 203, 3639, 389, 1991, 6542, 990, 12, 2316, 16, 2 ]
pragma solidity ^ 0.4.23; // tarot.etherealbazaar.com contract EtherealTarot { struct reading { // Struct uint8[] cards; bool[] upright; uint8 card_count; } mapping(address => reading) readings; uint8[78] cards; uint8 deckSize = 78; address public creator; constructor() public { creator = msg.sender; for (uint8 card = 0; card < deckSize; card++) { cards[card] = card; } } function draw(uint8 index, uint8 count) private { // put the drawn card at the end of the array // so the next random draw cannot contain // a card thats already been drawn uint8 drawnCard = cards[index]; uint8 tableIndex = deckSize - count - 1; cards[index] = cards[tableIndex]; cards[tableIndex] = drawnCard; } function draw_random_card(uint8 count) private returns(uint8) { uint8 random_card = random(deckSize - count, count); draw(random_card, count); return random_card; } function random(uint8 range, uint8 count) view private returns(uint8) { uint8 _seed = uint8( keccak256( abi.encodePacked( keccak256( abi.encodePacked( blockhash(block.number), _seed) ), now + count) ) ); return _seed % (range); } function random_bool(uint8 count) view private returns(bool){ return 0==random(2,count); } function spread(uint8 requested) private { // cards in the current spread uint8[] memory table = new uint8[](requested); // reversed cards aren't all bad! understand the shadow... bool[] memory upright = new bool[](requested); //Draw the whole spread for (uint8 position = 0; position < requested; position++) { table[position] = draw_random_card(position); upright[position] = random_bool(position); } readings[msg.sender]=reading(table,upright,requested); } function has_reading() view public returns(bool) { return readings[msg.sender].card_count!=0; } function reading_card_at(uint8 index) view public returns(uint8) { return readings[msg.sender].cards[index]; } // returning variable length arrays proved quite tricky... function reading_card_upright_at(uint8 index) view public returns(bool) { return readings[msg.sender].upright[index]; } function reading_card_count() view public returns(uint8){ return readings[msg.sender].card_count; } // Tarot by donation function withdraw() public { require(msg.sender == creator); creator.transfer(address(this).balance); } // 8 Different Spreads available function career_path() payable public { spread(7); } function celtic_cross() payable public { spread(10); } function past_present_future() payable public { spread(3); } function success() payable public { spread(5); } function spiritual_guidance() payable public { spread(8); } function single_card() payable public { spread(1); } function situation_challenge() payable public { spread(2); } function seventeen() payable public { spread(17); } }
returning variable length arrays proved quite tricky...
function reading_card_upright_at(uint8 index) view public returns(bool) { return readings[msg.sender].upright[index]; }
9,905,454
[ 1, 2463, 310, 2190, 769, 5352, 450, 2155, 25102, 433, 13055, 2777, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 6453, 67, 3327, 67, 416, 4083, 67, 270, 12, 11890, 28, 770, 13, 1476, 1071, 1135, 12, 6430, 13, 288, 203, 565, 327, 855, 899, 63, 3576, 18, 15330, 8009, 416, 4083, 63, 1615, 15533, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x62a6C3cD59bD079cB180D64608eDd9B8cc9E27F5/sources/contracts/L1/messaging/L1StandardBridge.sol
* @inheritdoc IL1StandardBridge/
function bridgeETH( uint32 _localGasLimit, uint32 _remoteGasLimit, bytes calldata _data ) external payable onlyEOA { _initiateETHBridge(msg.sender, msg.sender, _localGasLimit, _remoteGasLimit, _data); }
3,824,699
[ 1, 36, 10093, 467, 48, 21, 8336, 13691, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10105, 1584, 44, 12, 203, 3639, 2254, 1578, 389, 3729, 27998, 3039, 16, 203, 3639, 2254, 1578, 389, 7222, 27998, 3039, 16, 203, 3639, 1731, 745, 892, 389, 892, 203, 565, 262, 3903, 8843, 429, 1338, 41, 28202, 288, 203, 3639, 389, 2738, 3840, 1584, 44, 13691, 12, 3576, 18, 15330, 16, 1234, 18, 15330, 16, 389, 3729, 27998, 3039, 16, 389, 7222, 27998, 3039, 16, 389, 892, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.0; import "./Transaction.sol"; import "./TransactionRegistry.sol"; contract InsurableTransactionFactory { address payable public owner; TransactionRegistry internal registry; constructor(TransactionRegistry _registry) public { registry = _registry; owner = msg.sender; } event NewContractCreated (string msg, address contractAddress); /// @dev Factory method to create the insurable Transaction contracts /// @param counterParty the counter party of the Transaction contract /// @param name the name of Transaction contract /// @param max the maximum desired insurance coverage (%) for the Transaction contract /// @param desc the description for the Transaction contract /// @param premium the agreed upon premium (%) to pay out to insurers of the Transaction contract /// @return newContractAddress: the new Transaction address function create( address payable counterParty, bytes32 name, uint max, bytes32 desc, uint premium)external payable returns (Transaction newContractAddress) { require(counterParty!=address(0), "Counterparty cannot be null"); Transaction newContract = new Transaction(counterParty,name,desc,max,premium,msg.sender,uint(msg.value)); registry.registerOwnership(address(newContract),msg.sender); address(newContract).transfer(msg.value); emit NewContractCreated("Contract created successfully.", address(newContract)); return newContract; } }
@dev Factory method to create the insurable Transaction contracts @param counterParty the counter party of the Transaction contract @param name the name of Transaction contract @param max the maximum desired insurance coverage (%) for the Transaction contract @param desc the description for the Transaction contract @param premium the agreed upon premium (%) to pay out to insurers of the Transaction contract @return newContractAddress: the new Transaction address
function create( address payable counterParty, bytes32 name, uint max, bytes32 desc, uint premium)external payable returns (Transaction newContractAddress) { require(counterParty!=address(0), "Counterparty cannot be null"); Transaction newContract = new Transaction(counterParty,name,desc,max,premium,msg.sender,uint(msg.value)); registry.registerOwnership(address(newContract),msg.sender); address(newContract).transfer(msg.value); emit NewContractCreated("Contract created successfully.", address(newContract)); return newContract; }
12,779,949
[ 1, 1733, 707, 358, 752, 326, 2763, 7463, 5947, 20092, 225, 3895, 17619, 326, 3895, 18285, 434, 326, 5947, 6835, 225, 508, 326, 508, 434, 5947, 6835, 225, 943, 326, 4207, 6049, 2763, 295, 1359, 11196, 6142, 13, 364, 326, 5947, 6835, 225, 3044, 326, 2477, 364, 326, 5947, 6835, 225, 23020, 5077, 326, 1737, 15656, 12318, 23020, 5077, 6142, 13, 358, 8843, 596, 358, 2763, 295, 414, 434, 326, 5947, 6835, 327, 394, 8924, 1887, 30, 326, 394, 5947, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 12, 203, 3639, 1758, 8843, 429, 3895, 17619, 16, 7010, 3639, 1731, 1578, 508, 16, 203, 3639, 2254, 943, 16, 203, 3639, 1731, 1578, 3044, 16, 203, 3639, 2254, 23020, 5077, 13, 9375, 8843, 429, 1135, 261, 3342, 394, 8924, 1887, 13, 288, 203, 377, 203, 3639, 2583, 12, 7476, 17619, 5, 33, 2867, 12, 20, 3631, 315, 4789, 21214, 2780, 506, 446, 8863, 203, 540, 203, 3639, 5947, 394, 8924, 273, 394, 5947, 12, 7476, 17619, 16, 529, 16, 5569, 16, 1896, 16, 1484, 81, 5077, 16, 3576, 18, 15330, 16, 11890, 12, 3576, 18, 1132, 10019, 203, 540, 203, 3639, 4023, 18, 4861, 5460, 12565, 12, 2867, 12, 2704, 8924, 3631, 3576, 18, 15330, 1769, 203, 540, 203, 3639, 1758, 12, 2704, 8924, 2934, 13866, 12, 3576, 18, 1132, 1769, 203, 3639, 3626, 1166, 8924, 6119, 2932, 8924, 2522, 4985, 1199, 16, 1758, 12, 2704, 8924, 10019, 203, 3639, 327, 394, 8924, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a && c >= b); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20 { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract EtherDEX { using SafeMath for uint; address public admin; //the admin address address public feeAccount; //the account that will receive fees uint public feeMake; //percentage times (1 ether) uint public feeTake; //percentage times (1 ether) mapping(address => mapping(address => uint)) public tokens; //mapping of token addresses to mapping of account balances (token=0 means Ether) mapping(address => mapping(bytes32 => bool)) public orders; //mapping of user accounts to mapping of order hashes to booleans (true = submitted by user, equivalent to offchain signature) mapping(address => mapping(bytes32 => uint)) public orderFills; //mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled) address public previousContract; address public nextContract; bool public isContractDeprecated; uint public contractVersion; event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user); event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); event FundsMigrated(address user); modifier onlyAdmin() { require(msg.sender == admin); _; } constructor(address admin_, address feeAccount_, uint feeMake_, uint feeTake_, address _previousContract) public { admin = admin_; feeAccount = feeAccount_; feeMake = feeMake_; feeTake = feeTake_; previousContract = _previousContract; isContractDeprecated = false; //count new contract version if it's not the first if (previousContract != address(0)) { contractVersion = EtherDEX(previousContract).contractVersion() + 1; } else { contractVersion = 1; } } function() public payable { revert("Cannot send ETH directly to the Contract"); } function changeAdmin(address admin_) public onlyAdmin { admin = admin_; } function changeFeeAccount(address feeAccount_) public onlyAdmin { require(feeAccount_ != address(0)); feeAccount = feeAccount_; } function changeFeeMake(uint feeMake_) public onlyAdmin { if (feeMake_ > feeMake) revert("New fee cannot be higher than the old one"); feeMake = feeMake_; } function changeFeeTake(uint feeTake_) public onlyAdmin { if (feeTake_ > feeTake) revert("New fee cannot be higher than the old one"); feeTake = feeTake_; } function deprecate(bool deprecated_, address nextContract_) public onlyAdmin { isContractDeprecated = deprecated_; nextContract = nextContract_; } function deposit() public payable { tokens[0][msg.sender] = SafeMath.add(tokens[0][msg.sender], msg.value); emit Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); } function withdraw(uint amount) public { if (tokens[0][msg.sender] < amount) revert("Cannot withdraw more than you have"); tokens[0][msg.sender] = SafeMath.sub(tokens[0][msg.sender], amount); msg.sender.transfer(amount); //or .send() and check if https://ethereum.stackexchange.com/a/38642 emit Withdraw(0, msg.sender, amount, tokens[0][msg.sender]); } function depositToken(address token, uint amount) public { //remember to call ERC20Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. if (token == 0) revert("Cannot deposit ETH with depositToken method"); if (!ERC20(token).transferFrom(msg.sender, this, amount)) revert("You didn't call approve method on Token contract"); tokens[token][msg.sender] = SafeMath.add(tokens[token][msg.sender], amount); emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]); } function withdrawToken(address token, uint amount) public { if (token == 0) revert("Cannot withdraw ETH with withdrawToken method"); if (tokens[token][msg.sender] < amount) revert("Cannot withdraw more than you have"); tokens[token][msg.sender] = SafeMath.sub(tokens[token][msg.sender], amount); if (!ERC20(token).transfer(msg.sender, amount)) revert("Error while transfering tokens"); emit Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); } function balanceOf(address token, address user) public view returns (uint) { return tokens[token][user]; } function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) public { bytes32 hash = sha256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce)); orders[msg.sender][hash] = true; emit Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender); } function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) public { //amount is in amountGet terms bytes32 hash = sha256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce)); if (!( (orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s) == user) && block.number <= expires && SafeMath.add(orderFills[user][hash], amount) <= amountGet )) revert("Validation error or order expired or not enough volume to trade"); tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount); orderFills[user][hash] = SafeMath.add(orderFills[user][hash], amount); emit Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender); } function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) public view returns (bool) { return (tokens[tokenGet][sender] >= amount && availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount); } function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) public view returns (uint) { bytes32 hash = sha256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce)); if (!((orders[user][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s) == user) && block.number <= expires)) return 0; uint available1 = SafeMath.sub(amountGet, orderFills[user][hash]); uint available2 = SafeMath.mul(tokens[tokenGive][user], amountGet) / amountGive; if (available1 < available2) return available1; return available2; } function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user) public view returns (uint) { bytes32 hash = sha256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce)); return orderFills[user][hash]; } function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) public { bytes32 hash = sha256(abi.encodePacked(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce)); if (!(orders[msg.sender][hash] || ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s) == msg.sender)) revert("Validation error"); orderFills[msg.sender][hash] = amountGet; emit Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s); } function migrateFunds(address[] tokens_) public { // Get the latest successor in the chain require(nextContract != address(0)); EtherDEX newExchange = findNewExchangeContract(); // Ether migrateEther(newExchange); // Tokens migrateTokens(newExchange, tokens_); emit FundsMigrated(msg.sender); } function depositEtherForUser(address _user) public payable { require(!isContractDeprecated); require(_user != address(0)); require(msg.value > 0); EtherDEX caller = EtherDEX(msg.sender); require(caller.contractVersion() > 0); // Make sure it's an exchange account tokens[0][_user] = tokens[0][_user].add(msg.value); } function depositTokenForUser(address _token, uint _amount, address _user) public { require(!isContractDeprecated); require(_token != address(0)); require(_user != address(0)); require(_amount > 0); EtherDEX caller = EtherDEX(msg.sender); require(caller.contractVersion() > 0); // Make sure it's an exchange account if (!ERC20(_token).transferFrom(msg.sender, this, _amount)) { revert(); } tokens[_token][_user] = tokens[_token][_user].add(_amount); } function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { uint feeMakeXfer = SafeMath.mul(amount, feeMake) / (1 ether); uint feeTakeXfer = SafeMath.mul(amount, feeTake) / (1 ether); tokens[tokenGet][msg.sender] = SafeMath.sub(tokens[tokenGet][msg.sender], SafeMath.add(amount, feeTakeXfer)); tokens[tokenGet][user] = SafeMath.add(tokens[tokenGet][user], SafeMath.sub(amount, feeMakeXfer)); tokens[tokenGet][feeAccount] = SafeMath.add(tokens[tokenGet][feeAccount], SafeMath.add(feeMakeXfer, feeTakeXfer)); tokens[tokenGive][user] = SafeMath.sub(tokens[tokenGive][user], SafeMath.mul(amountGive, amount) / amountGet); tokens[tokenGive][msg.sender] = SafeMath.add(tokens[tokenGive][msg.sender], SafeMath.mul(amountGive, amount) / amountGet); } function findNewExchangeContract() private view returns (EtherDEX) { EtherDEX newExchange = EtherDEX(nextContract); for (uint16 n = 0; n < 20; n++) {// We will look past 20 contracts in the future address nextContract_ = newExchange.nextContract(); if (nextContract_ == address(this)) {// Circular succession revert(); } if (nextContract_ == address(0)) {// We reached the newest, stop break; } newExchange = EtherDEX(nextContract_); } return newExchange; } function migrateEther(EtherDEX newExchange) private { uint etherAmount = tokens[0][msg.sender]; if (etherAmount > 0) { tokens[0][msg.sender] = 0; newExchange.depositEtherForUser.value(etherAmount)(msg.sender); } } function migrateTokens(EtherDEX newExchange, address[] tokens_) private { for (uint16 n = 0; n < tokens_.length; n++) { address token = tokens_[n]; require(token != address(0)); // 0 = Ether, we handle it above uint tokenAmount = tokens[token][msg.sender]; if (tokenAmount == 0) { continue; } if (!ERC20(token).approve(newExchange, tokenAmount)) { revert(); } tokens[token][msg.sender] = 0; newExchange.depositTokenForUser(token, tokenAmount, msg.sender); } } }
We reached the newest, stop
if (nextContract_ == address(0)) {
13,052,404
[ 1, 3218, 8675, 326, 19824, 16, 2132, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 309, 261, 4285, 8924, 67, 422, 1758, 12, 20, 3719, 288, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./Types.sol"; import "./IASRegistry.sol"; import "./IASResolver.sol"; /** * @title The global AS registry. */ contract ASRegistry is IASRegistry { error AlreadyExists(); string public constant VERSION = "0.8"; // The global mapping between AS records and their IDs. mapping(bytes32 => ASRecord) private _registry; // The global counter for the total number of attestations. uint256 private _asCount; /** * @inheritdoc IASRegistry */ function register(bytes calldata schema, IASResolver resolver) external returns (bytes32) { uint256 index = ++_asCount; ASRecord memory asRecord = ASRecord({uuid: EMPTY_UUID, index: index, schema: schema, resolver: resolver}); bytes32 uuid = _getUUID(asRecord); if (_registry[uuid].uuid != EMPTY_UUID) { revert AlreadyExists(); } asRecord.uuid = uuid; _registry[uuid] = asRecord; emit Registered(uuid, index, schema, resolver, msg.sender); return uuid; } /** * @inheritdoc IASRegistry */ function getAS(bytes32 uuid) external view returns (ASRecord memory) { return _registry[uuid]; } /** * @inheritdoc IASRegistry */ function getASCount() external view returns (uint256) { return _asCount; } /** * @dev Calculates a UUID for a given AS. * * @param asRecord The input AS. * * @return AS UUID. */ function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) { return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver)); } }
* @dev Calculates a UUID for a given AS. @param asRecord The input AS. @return AS UUID./
function _getUUID(ASRecord memory asRecord) private pure returns (bytes32) { return keccak256(abi.encodePacked(asRecord.schema, asRecord.resolver)); }
13,096,871
[ 1, 10587, 279, 5866, 364, 279, 864, 5355, 18, 225, 487, 2115, 1021, 810, 5355, 18, 327, 5355, 5866, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 5562, 12, 3033, 2115, 3778, 487, 2115, 13, 3238, 16618, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 327, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 345, 2115, 18, 4821, 16, 487, 2115, 18, 14122, 10019, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xfCc29b1BB55c4f015f63f5a0FA0B9338414aec68/sources/AyreFarmV2.sol
sushiPerBlock = 88888888888888888;
function initialize() public initializer { __Ownable_init(); sushiPerBlock = 1288244766505636; harvestFee = 1e18; additionalRewards.push(AdditionalReward({ reward: 1000 })); additionalRewards.push(AdditionalReward({ reward: 3333 })); additionalRewards.push(AdditionalReward({ reward: 300 })); }
11,042,115
[ 1, 87, 1218, 77, 2173, 1768, 273, 1725, 5482, 5482, 5482, 5482, 5482, 5482, 5482, 5482, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 1435, 1071, 12562, 288, 203, 3639, 1001, 5460, 429, 67, 2738, 5621, 203, 203, 3639, 272, 1218, 77, 2173, 1768, 273, 2593, 5482, 3247, 9462, 6028, 3361, 4313, 5718, 31, 203, 3639, 17895, 26923, 14667, 273, 404, 73, 2643, 31, 203, 203, 3639, 3312, 17631, 14727, 18, 6206, 12, 10552, 17631, 1060, 12590, 203, 3639, 19890, 30, 4336, 203, 3639, 289, 10019, 203, 3639, 3312, 17631, 14727, 18, 6206, 12, 10552, 17631, 1060, 12590, 203, 3639, 19890, 30, 890, 3707, 23, 203, 3639, 289, 10019, 203, 3639, 3312, 17631, 14727, 18, 6206, 12, 10552, 17631, 1060, 12590, 203, 3639, 19890, 30, 11631, 203, 3639, 289, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * WorldCoin: https://worldcoin.cash */ //====== Open Zeppelin Library ===== /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } //====== BurnableToken ===== contract BurnableToken is StandardToken { using SafeMath for uint256; event Burn(address indexed from, uint256 amount); event BurnRewardIncreased(address indexed from, uint256 value); /** * @dev Sending ether to contract increases burning reward */ function() payable public { if(msg.value > 0){ BurnRewardIncreased(msg.sender, msg.value); } } /** * @dev Calculates how much ether one will receive in reward for burning tokens * @param _amount of tokens to be burned */ function burnReward(uint256 _amount) public constant returns(uint256){ return this.balance.mul(_amount).div(totalSupply); } /** * @dev Burns tokens and send reward * This is internal function because it DOES NOT check * if _from has allowance to burn tokens. * It is intended to be used in transfer() and transferFrom() which do this check. * @param _from The address which you want to burn tokens from * @param _amount of tokens to be burned */ function burn(address _from, uint256 _amount) internal returns(bool){ require(balances[_from] >= _amount); uint256 reward = burnReward(_amount); assert(this.balance - reward > 0); balances[_from] = balances[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); //assert(totalSupply >= 0); //Check is not needed because totalSupply.sub(value) will already throw if this condition is not met _from.transfer(reward); Burn(_from, _amount); Transfer(_from, address(0), _amount); return true; } /** * @dev Transfers or burns tokens * Burns tokens transferred to this contract itself or to zero address * @param _to The address to transfer to or token contract address to burn. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { if( (_to == address(this)) || (_to == 0) ){ return burn(msg.sender, _value); }else{ return super.transfer(_to, _value); } } /** * @dev Transfer tokens from one address to another * or burns them if _to is this contract or zero address * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if( (_to == address(this)) || (_to == 0) ){ var _allowance = allowed[_from][msg.sender]; //require (_value <= _allowance); //Check is not needed because _allowance.sub(_value) will already throw if this condition is not met allowed[_from][msg.sender] = _allowance.sub(_value); return burn(_from, _value); }else{ return super.transferFrom(_from, _to, _value); } } } //====== WorldCoin Contracts ===== /** * @title WorldCoin token */ contract WorldCoin is BurnableToken, MintableToken, HasNoContracts, HasNoTokens { //MintableToken is StandardToken, Ownable using SafeMath for uint256; string public name = "World Coin Network"; string public symbol = "WCN"; uint256 public decimals = 18; /** * Allow transfer only after crowdsale finished */ modifier canTransfer() { require(mintingFinished); _; } function transfer(address _to, uint256 _value) canTransfer public returns (bool) { return BurnableToken.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer public returns (bool) { return BurnableToken.transferFrom(_from, _to, _value); } } /** * @title WorldCoin Crowdsale */ contract WorldCoinCrowdsale is Ownable, HasNoContracts, HasNoTokens { using SafeMath for uint256; uint32 private constant PERCENT_DIVIDER = 100; WorldCoin public token; struct Round { uint256 start; //Timestamp of crowdsale round start uint256 end; //Timestamp of crowdsale round end uint256 rate; //Rate: how much TOKEN one will get fo 1 ETH during this round } Round[] public rounds; //Array of crowdsale rounds uint256 public founderPercent; //how many tokens will be sent to founder (percent of purshased token) uint256 public partnerBonusPercent; //referral partner bonus (percent of purshased token) uint256 public referralBonusPercent;//referral buyer bonus (percent of purshased token) uint256 public hardCap; //Maximum amount of tokens mined uint256 public totalCollected; //total amount of collected funds (in ethereum wei) uint256 public tokensMinted; //total amount of minted tokens bool public finalized; //crowdsale is finalized /** * @dev WorldCoin Crowdsale Contract * @param _founderPercent Amount of tokens sent to founder with each purshase (percent of purshased token) * @param _partnerBonusPercent Referral partner bonus (percent of purshased token) * @param _referralBonusPercent Referral buyer bonus (percent of purshased token) * @param _hardCap Maximum amount of ether (in wei) to be collected during crowdsale * @param roundStarts List of round start timestams * @param roundEnds List of round end timestams * @param roundRates List of round rates (tokens for 1 ETH) */ function WorldCoinCrowdsale ( uint256 _founderPercent, uint256 _partnerBonusPercent, uint256 _referralBonusPercent, uint256 _hardCap, uint256[] roundStarts, uint256[] roundEnds, uint256[] roundRates ) public { //Check all paramaters are correct and create rounds require(_hardCap > 0); //Need something to sell require( (roundStarts.length > 0) && //There should be at least one round (roundStarts.length == roundEnds.length) && (roundStarts.length == roundRates.length) ); uint256 prevRoundEnd = now; rounds.length = roundStarts.length; //initialize rounds array for(uint8 i=0; i < roundStarts.length; i++){ rounds[i] = Round(roundStarts[i], roundEnds[i], roundRates[i]); Round storage r = rounds[i]; require(prevRoundEnd <= r.start); require(r.start < r.end); require(r.rate > 0); prevRoundEnd = rounds[i].end; } hardCap = _hardCap; partnerBonusPercent = _partnerBonusPercent; referralBonusPercent = _referralBonusPercent; founderPercent = _founderPercent; //founderPercentWithReferral = founderPercent * (rate + partnerBonusPercent + referralBonusPercent) / rate; //Did not use SafeMath here, because this parameters defined by contract creator should not be malicious. Also have checked result on the next line. //assert(founderPercentWithReferral >= founderPercent); token = new WorldCoin(); } /** * @dev Fetches current Round number * @return round number (index in rounds array + 1) or 0 if none */ function currentRoundNum() constant public returns(uint8) { for(uint8 i=0; i < rounds.length; i++){ if( (now > rounds[i].start) && (now <= rounds[i].end) ) return i+1; } return 0; } /** * @dev Fetches current rate (how many tokens you get for 1 ETH) * @return calculated rate or zero if no round of crowdsale is running */ function currentRate() constant public returns(uint256) { uint8 roundNum = currentRoundNum(); if(roundNum == 0) { return 0; }else{ return rounds[roundNum-1].rate; } } function firstRoundStartTimestamp() constant public returns(uint256){ return rounds[0].start; } function lastRoundEndTimestamp() constant public returns(uint256){ return rounds[rounds.length - 1].end; } /** * @dev Shows if crowdsale is running */ function crowdsaleRunning() constant public returns(bool){ return !finalized && (tokensMinted < hardCap) && (currentRoundNum() > 0); } /** * @dev Buy WorldCoin tokens */ function() payable public { sale(msg.sender, 0x0); } /** * @dev Buy WorldCoin tokens witn referral program */ function sale(address buyer, address partner) public payable { if(!crowdsaleRunning()) revert(); require(msg.value > 0); uint256 rate = currentRate(); assert(rate > 0); uint256 referralTokens; uint256 partnerTokens; uint256 ownerTokens; uint256 tokens = rate.mul(msg.value); assert(tokens > 0); totalCollected = totalCollected.add(msg.value); if(partner == 0x0){ ownerTokens = tokens.mul(founderPercent).div(PERCENT_DIVIDER); mintTokens(buyer, tokens); mintTokens(owner, ownerTokens); }else{ partnerTokens = tokens.mul(partnerBonusPercent).div(PERCENT_DIVIDER); referralTokens = tokens.mul(referralBonusPercent).div(PERCENT_DIVIDER); ownerTokens = (tokens.add(partnerTokens).add(referralTokens)).mul(founderPercent).div(PERCENT_DIVIDER); uint256 totalBuyerTokens = tokens.add(referralTokens); mintTokens(buyer, totalBuyerTokens); mintTokens(partner, partnerTokens); mintTokens(owner, ownerTokens); } } /** * @notice Mint tokens for purshases with Non-Ether currencies * @param beneficiary whom to send tokend * @param amount how much tokens to send * param message reason why we are sending tokens (not stored anythere, only in transaction itself) */ function saleNonEther(address beneficiary, uint256 amount, string /*message*/) public onlyOwner { mintTokens(beneficiary, amount); } /** * @notice Updates rate for the round */ function setRoundRate(uint32 roundNum, uint256 rate) public onlyOwner { require(roundNum < rounds.length); rounds[roundNum].rate = rate; } /** * @notice Sends collected funds to owner * May be executed only if goal reached and no refunds are possible */ function claimEther() public onlyOwner { if(this.balance > 0){ owner.transfer(this.balance); } } /** * @notice Finalizes ICO when one of conditions met: * - end time reached OR * - no more tokens available (cap reached) OR * - message sent by owner */ function finalizeCrowdsale() public { require ( (now > lastRoundEndTimestamp()) || (totalCollected == hardCap) || (msg.sender == owner) ); finalized = token.finishMinting(); token.transferOwnership(owner); if(this.balance > 0){ owner.transfer(this.balance); } } /** * @dev Helper function to mint tokens and increase tokensMinted counter */ function mintTokens(address beneficiary, uint256 amount) internal { tokensMinted = tokensMinted.add(amount); require(tokensMinted <= hardCap); assert(token.mint(beneficiary, amount)); } }
referral partner bonus (percent of purshased token)
uint256 public partnerBonusPercent;
12,947,952
[ 1, 1734, 29084, 19170, 324, 22889, 261, 8849, 434, 5405, 674, 8905, 1147, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 19170, 38, 22889, 8410, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xb474f03c2c1e15596260CDa307f7827cdD3Fb749/sources/src/BearCave.sol
Feature Toggle... what if we just make a feature toggle lib...
bool public distributeWithMint;
8,391,000
[ 1, 4595, 399, 9891, 2777, 4121, 309, 732, 2537, 1221, 279, 2572, 10486, 2561, 2777, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 25722, 1190, 49, 474, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0xAFF7035f192F3a6A71833Eb66563Af09653e848E/sources/tests/Fingers/FingersInTheNose.sol
% of purchases goes to the artist
uint artistAllocation;
13,199,902
[ 1, 9, 434, 5405, 343, 3304, 13998, 358, 326, 15469, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 15469, 17353, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x98BbEB7e4D59a3E6A3bc6422E5Ff73906302CdE0/sources/LiquidityGeneration.sol
Open for Two Weeks
endTime = block.timestamp.add(1210000);
663,989
[ 1, 3678, 364, 16896, 10527, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 13859, 273, 1203, 18, 5508, 18, 1289, 12, 2138, 23899, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity =0.8.13; import "@openzeppelin-v4/contracts/utils/introspection/IERC165.sol"; import "@openzeppelin-v4/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "../interfaces/IQuoteToken.sol"; contract SimpleQuotationMetadata is IQuoteToken, IERC165 { address public immutable quoteToken; constructor(address quoteToken_) { quoteToken = quoteToken_; } /// @inheritdoc IQuoteToken function quoteTokenName() public view virtual override returns (string memory) { return getStringOrBytes32(quoteToken, IERC20Metadata.name.selector); } /// @inheritdoc IQuoteToken function quoteTokenAddress() public view virtual override returns (address) { return quoteToken; } /// @inheritdoc IQuoteToken function quoteTokenSymbol() public view virtual override returns (string memory) { return getStringOrBytes32(quoteToken, IERC20Metadata.symbol.selector); } /// @inheritdoc IQuoteToken function quoteTokenDecimals() public view virtual override returns (uint8) { (bool success, bytes memory result) = quoteToken.staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); if (!success) return 18; // Return 18 by default return abi.decode(result, (uint8)); } /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IQuoteToken).interfaceId; } function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) { // Calculate string length uint256 i = 0; while (i < 32 && _bytes32[i] != 0) ++i; bytes memory bytesArray = new bytes(i); // Extract characters for (i = 0; i < 32 && _bytes32[i] != 0; ++i) bytesArray[i] = _bytes32[i]; return string(bytesArray); } function getStringOrBytes32(address contractAddress, bytes4 selector) internal view returns (string memory) { (bool success, bytes memory result) = contractAddress.staticcall(abi.encodeWithSelector(selector)); if (!success) return ""; return result.length == 32 ? bytes32ToString(bytes32(result)) : abi.decode(result, (string)); } }
@inheritdoc IQuoteToken
function quoteTokenDecimals() public view virtual override returns (uint8) { (bool success, bytes memory result) = quoteToken.staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); return abi.decode(result, (uint8)); }
2,547,357
[ 1, 36, 10093, 467, 10257, 1345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3862, 1345, 31809, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 563, 13, 273, 3862, 1345, 18, 3845, 1991, 12, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 45, 654, 39, 3462, 2277, 18, 31734, 18, 9663, 13, 203, 3639, 11272, 203, 203, 3639, 327, 24126, 18, 3922, 12, 2088, 16, 261, 11890, 28, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY171() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF784(address account) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER754(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE384(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE522(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM156(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER68(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL81(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER324() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function TOTALSUPPLY171() public view returns (uint) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF784(address account) public view returns (uint) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER754(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER587(_MSGSENDER324(), recipient, amount); return true; } function ALLOWANCE384(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE522(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE274(_MSGSENDER324(), spender, amount); return true; } function TRANSFERFROM156(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER587(sender, recipient, amount); _APPROVE274(sender, _MSGSENDER324(), _allowances[sender][_MSGSENDER324()].SUB131(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE835(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE274(_MSGSENDER324(), spender, _allowances[_MSGSENDER324()][spender].ADD951(addedValue)); return true; } function DECREASEALLOWANCE568(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE274(_MSGSENDER324(), spender, _allowances[_MSGSENDER324()][spender].SUB131(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER587(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB131(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD951(amount); emit TRANSFER68(sender, recipient, amount); } function _MINT189(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD951(amount); _balances[account] = _balances[account].ADD951(amount); emit TRANSFER68(address(0), account, amount); } function _BURN372(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB131(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB131(amount); emit TRANSFER68(account, address(0), amount); } function _APPROVE274(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING 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 APPROVAL81(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME128() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL200() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS712() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } library SafeMath { function ADD951(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB131(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB131(a, b, "SafeMath: subtraction overflow"); } function SUB131(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL231(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV400(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV400(a, b, "SafeMath: division by zero"); } function DIV400(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function ISCONTRACT647(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function SAFETRANSFER747(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.TRANSFER754.selector, to, value)); } function SAFETRANSFERFROM172(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.TRANSFERFROM156.selector, from, to, value)); } function SAFEAPPROVE759(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE384(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.APPROVE522.selector, spender, value)); } function CALLOPTIONALRETURN719(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT647(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract YFiG is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; constructor () public ERC20Detailed("YFiGlobal.Finance", "YFiG", 18) { governance = msg.sender; } function MINT296(address account, uint amount) public { //inject NONSTANDARD NAMING require(minters[msg.sender], "!minter"); _MINT189(account, amount); } function SETGOVERNANCE402(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function ADDMINTER585(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = true; } function REMOVEMINTER114(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = false; } }
inject NONSTANDARD NAMING
event APPROVAL81(address indexed owner, address indexed spender, uint value);
12,662,862
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 14410, 3373, 2669, 11861, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 460, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]