file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
/** *Submitted for verification at Etherscan.io on 2021-03-23 */ // // &&&& // &&&& // &&&& // &&&& &&&&&&&&& &&&&&&&&&&&& &&&&&&&&&&/ &&&&.&&&&&&&&& // &&&&&&&&& &&&&& &&&&&& &&&&&, &&&&& &&&&& &&&&&&&& &&&& // &&&&&& &&&& &&&&# &&&& &&&&& &&&&& &&&&&& &&&&& // &&&&& &&&&/ &&&& &&&& #&&&& &&&& &&&&& // &&&& &&&& &&&&& &&&& &&&& &&&&& &&&&& // %%%% /%%%% %%%%%% %%%%%% %%%% %%%%%%%%% %%%%% // %%%%% %%%% %%%%%%%%%%% %%%% %%%%%% %%%% // %%%% // %%%% // %%%% // // File @uniswap/v2-core/contracts/interfaces/[email protected] 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; } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <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 SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/math/[email protected] 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); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // File @openzeppelin/contracts/token/ERC777/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/HoprFarm.sol // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.6.12; /** * 5 million HOPR tokens are allocated as incentive for liquidity providers on uniswap. * This incentive will be distributed on an approx. weekly-basis over 3 months (13 weeks) * Liquidity providers (LPs) can deposit their LP-tokens (UniswapV2Pair token for HOPR-DAI) * to this HoprFarm contract for at least 1 week (minimum deposit period) to receive rewards. */ contract HoprFarm is IERC777Recipient, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using Arrays for uint256[]; uint256 public constant TOTAL_INCENTIVE = 5000000 ether; uint256 public constant WEEKLY_BLOCK_NUMBER = 44800; // Taking 13.5 s/block as average block time. thus 7*24*60*60/13.5 = 44800 blocks per week. uint256 public constant TOTAL_CLAIM_PERIOD = 13; // Incentives are released over a period of 13 weeks. uint256 public constant WEEKLY_INCENTIVE = 384615384615384615384615; // 5000000/13 weeks There is very small amount of remainder for the last week (+5 wei) // setup ERC1820 IERC1820Registry private constant ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 private constant TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); struct LiquidityProvider { mapping(uint256=>uint256) eligibleBalance; // Amount of liquidity tokens uint256 claimedUntil; // the last period where the liquidity provider has claimed tokens uint256 currentBalance; } // an ascending block numbers of start/end of each farming interval. // E.g. the first farming interval is (distributionBlocks[0], distributionBlocks[1]]. uint256[] public distributionBlocks; mapping(uint256=>uint256) public eligibleLiquidityPerPeriod; mapping(address=>LiquidityProvider) public liquidityProviders; uint256 public totalPoolBalance; uint256 public claimedIncentive; address public multisig; IERC20 public pool; IERC20 public hopr; event TokenAdded(address indexed provider, uint256 indexed period, uint256 amount); event TokenRemoved(address indexed provider, uint256 indexed period, uint256 amount); event IncentiveClaimed(address indexed provider, uint256 indexed until, uint256 amount); /** * @dev Modifier to check address is multisig */ modifier onlyMultisig(address adr) { require(adr == multisig, "HoprFarm: Only DAO multisig"); _; } /** * @dev provides the farming schedule. * @param _pool address Address of the HOPR-DAI uniswap pool. * @param _token address Address of the HOPR token. * @param _multisig address Address of the HOPR DAO multisig. */ constructor(address _pool, address _token, address _multisig) public { require(IUniswapV2Pair(_pool).token0() == _token || IUniswapV2Pair(_pool).token1() == _token, "HoprFarm: wrong token address"); pool = IERC20(_pool); hopr = IERC20(_token); multisig = _multisig; distributionBlocks.push(0); ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } /** * @dev ERC777 hook triggered when multisig send HOPR token to this contract. * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes hex string of the starting block number. e.g. "0xb66bbd" for 11955133. It should not be longer than 3 bytes * @param operatorData bytes extra information provided by the operator (if any) */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, // solhint-disable-next-line no-unused-vars bytes calldata operatorData ) external override onlyMultisig(from) nonReentrant { require(msg.sender == address(hopr), "HoprFarm: Sender must be HOPR token"); require(to == address(this), "HoprFarm: Must be sending tokens to HOPR farm"); require(amount == TOTAL_INCENTIVE, "HoprFarm: Only accept 5 million HOPR token"); // take block number from userData, varies from 0x000000 to 0xffffff. // This value is sufficient as 0xffff will be in March 2023. require(userData.length == 3, "HoprFarm: Start block number needs to have three bytes"); require(distributionBlocks[0] == 0, "HoprFarm: Not initialized yet."); bytes32 m; assembly { // it first loads the userData at the position 228 = 4 + 32 * 7, // where 4 is the method signature and 7 is the storage of userData // Then bit shift the right-padded bytes32 to remove all the padded zeros // Given the blocknumber is not longer than 3 bytes, bitwise it needs to shift // log2(16) * (32 - 3) * 2 = 232 m := shr(232, calldataload(228)) } // update distribution blocks uint256 startBlock = uint256(m); require(startBlock >= block.number, "HoprFarm: Start block number should be in the future"); distributionBlocks[0] = startBlock; for (uint256 i = 1; i <= TOTAL_CLAIM_PERIOD; i++) { distributionBlocks.push(startBlock + i * WEEKLY_BLOCK_NUMBER); } } /** * @dev Multisig can recover tokens (pool tokens/hopr tokens/any other random tokens) * @param token Address of the token to be recovered. */ function recoverToken(address token) external onlyMultisig(msg.sender) nonReentrant { if (token == address(hopr)) { hopr.safeTransfer(multisig, hopr.balanceOf(address(this)).add(claimedIncentive).sub(TOTAL_INCENTIVE)); } else if (token == address(pool)) { pool.safeTransfer(multisig, pool.balanceOf(address(this)).sub(totalPoolBalance)); } else { IERC20(token).safeTransfer(multisig, IERC20(token).balanceOf(address(this))); } } /** * @dev Claim incenvtives for an account. Update total claimed incentive. * @param provider Account of liquidity provider */ function claimFor(address provider) external nonReentrant { uint256 currentPeriod = distributionBlocks.findUpperBound(block.number); _claimFor(currentPeriod, provider); } /** * @dev liquidity provider deposits their Uniswap HOPR-DAI tokens to the contract * It updates the current balance and the eligible farming balance * Thanks to `permit` function of UNI token (see below, link to source code), * https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol * LPs do not need to call `approve` seperately. `spender` is this farm contract. * This function can be called by anyone with a valid signature of liquidity provider. * @param amount Amount of pool token to be staked into the contract. It is also the amount in the signature. * @param owner Address of the liquidity provider. * @param deadline Timestamp after which the signature is no longer valid. * @param v ECDSA signature. * @param r ECDSA signature. * @param s ECDSA signature. */ function openFarmWithPermit(uint256 amount, address owner, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant { IUniswapV2Pair(address(pool)).permit(owner, address(this), amount, deadline, v, r, s); _openFarm(amount, owner); } /** * @dev Called by liquidty provider to deposit their Uniswap HOPR-DAI tokens to the contract * It updates the current balance and the eligible farming balance * @notice An `apprpove(<farm contract>, amount)` needs to be called prior to `openFarm` * @param amount Amount of pool token to be staked into the contract. */ function openFarm(uint256 amount) external nonReentrant { _openFarm(amount, msg.sender); } /** * @dev Claims all the reward until current block number and close the farm. */ function claimAndClose() external nonReentrant { // get current farm period uint256 currentPeriod = distributionBlocks.findUpperBound(block.number); _claimFor(currentPeriod, msg.sender); _closeFarm(currentPeriod, msg.sender, liquidityProviders[msg.sender].currentBalance); } /** * @dev liquidity provider removes their Uniswap HOPR-DAI tokens to the contract * It updates the current balance and the eligible farming balance * @param amount Amount of pool token to be removed from the contract. */ function closeFarm(uint256 amount) external nonReentrant { // update balance to the right phase uint256 currentPeriod = distributionBlocks.findUpperBound(block.number); _closeFarm(currentPeriod, msg.sender, amount); } /** * @dev returns the first index that contains a value greater or equal to the current `block.number` * If all numbers are strictly below block.number, returns array length. * @notice get the current farm period. 0 means "not started", 1 means "1st period", ... * If the returned value is larger than `maxFarmPeriod`, it means farming is "closed" */ function currentFarmPeriod() public view returns (uint256) { return distributionBlocks.findUpperBound(block.number); } /** * @dev calculate virtual return based on current staking. Amount of tokens one can claim in the next period. * @param amountToStake Amount of pool token that a liquidity provider would stake */ function currentFarmIncentive(uint256 amountToStake) public view returns (uint256) { uint256 currentPeriod = distributionBlocks.findUpperBound(block.number); if (currentPeriod >= TOTAL_CLAIM_PERIOD) { return 0; } return WEEKLY_INCENTIVE.mul(amountToStake).div(eligibleLiquidityPerPeriod[currentPeriod+1].add(amountToStake)); } /** * @dev Get the total amount of incentive to be claimed by the liquidity provider. * @param provider Account of liquidity provider */ function incentiveToBeClaimed(address provider) public view returns (uint256) { uint256 currentPeriod = distributionBlocks.findUpperBound(block.number); return _incentiveToBeClaimed(currentPeriod, provider); } /** * @dev update the liquidity token balance, of which is used for calculating the result of farming * It updates the balance for the following periods. For the previous period, if the balance reduces * the eligible balance of the previous round reduces. If the balance increases, it only affects the * following rounds. * @param account Address of the liquidity provider * @param newBalance Latest balance * @param currentPeriod Index of the farming period at current block number. */ function updateEligibleBalance(address account, uint256 newBalance, uint256 currentPeriod) internal { if (currentPeriod > 0) { uint256 balanceFromLastPeriod = liquidityProviders[account].eligibleBalance[currentPeriod - 1]; if (balanceFromLastPeriod > newBalance) { liquidityProviders[account].eligibleBalance[currentPeriod - 1] = newBalance; eligibleLiquidityPerPeriod[currentPeriod - 1] = eligibleLiquidityPerPeriod[currentPeriod - 1].sub(balanceFromLastPeriod).add(newBalance); } } uint256 newEligibleLiquidityPerPeriod = eligibleLiquidityPerPeriod[currentPeriod].sub(liquidityProviders[account].eligibleBalance[currentPeriod]).add(newBalance); for (uint256 i = currentPeriod; i < TOTAL_CLAIM_PERIOD; i++) { liquidityProviders[account].eligibleBalance[i] = newBalance; eligibleLiquidityPerPeriod[i] = newEligibleLiquidityPerPeriod; } } /** * @dev liquidity provider deposits their Uniswap HOPR-DAI tokens to the contract * It updates the current balance and the eligible farming balance * @param amount Amount of pool token to be staked into the contract. * @param provider Address of the liquidity provider. */ function _openFarm(uint256 amount, address provider) internal { // update balance to the right phase uint256 currentPeriod = distributionBlocks.findUpperBound(block.number); require(currentPeriod < TOTAL_CLAIM_PERIOD, "HoprFarm: Farming ended"); // always add currentBalance uint256 newBalance = liquidityProviders[provider].currentBalance.add(amount); liquidityProviders[provider].currentBalance = newBalance; totalPoolBalance = totalPoolBalance.add(amount); // update eligible balance updateEligibleBalance(provider, newBalance, currentPeriod); // transfer token pool.safeTransferFrom(provider, address(this), amount); // emit event emit TokenAdded(provider, currentPeriod, amount); } /** * @dev Claim incenvtives for an account. Update total claimed incentive. * @param currentPeriod Current farm period * @param provider Account of liquidity provider */ function _claimFor(uint256 currentPeriod, address provider) internal { require(currentPeriod > 1, "HoprFarm: Too early to claim"); uint256 farmed = _incentiveToBeClaimed(currentPeriod, provider); require(farmed > 0, "HoprFarm: Nothing to claim"); liquidityProviders[provider].claimedUntil = currentPeriod - 1; claimedIncentive = claimedIncentive.add(farmed); // transfer farmed tokens to the provider hopr.safeTransfer(provider, farmed); emit IncentiveClaimed(provider, currentPeriod - 1, farmed); } /** * @dev liquidity provider removes their Uniswap HOPR-DAI tokens to the contract * It updates the current balance and the eligible farming balance * @param currentPeriod Current farm period * @param provider Account of liquidity provider * @param amount Amount of pool token to be removed from the contract. */ function _closeFarm(uint256 currentPeriod, address provider, uint256 amount) internal { // always add currentBalance uint256 newBalance = liquidityProviders[provider].currentBalance.sub(amount); liquidityProviders[provider].currentBalance = newBalance; totalPoolBalance = totalPoolBalance.sub(amount); // update eligible balance updateEligibleBalance(provider, newBalance, currentPeriod); // transfer token pool.safeTransfer(provider, amount); // emit event emit TokenRemoved(provider, currentPeriod, amount); } /** * @dev Private function that gets the total amount of incentive to be claimed by the liquidity provider. * @param currentPeriod Current farm period * @param provider Account of liquidity provider */ function _incentiveToBeClaimed(uint256 currentPeriod, address provider) private view returns (uint256) { uint256 claimedPeriod = liquidityProviders[provider].claimedUntil; if (currentPeriod < 1 || claimedPeriod >= currentPeriod) { return 0; } uint256 farmed; for (uint256 i = claimedPeriod; i < currentPeriod - 1; i++) { if (eligibleLiquidityPerPeriod[i] > 0) { farmed = farmed.add(WEEKLY_INCENTIVE.mul(liquidityProviders[provider].eligibleBalance[i]).div(eligibleLiquidityPerPeriod[i])); } } return farmed; } }
* @dev Called by liquidty provider to deposit their Uniswap HOPR-DAI tokens to the contract It updates the current balance and the eligible farming balance @notice An `apprpove(<farm contract>, amount)` needs to be called prior to `openFarm` @param amount Amount of pool token to be staked into the contract./
function openFarm(uint256 amount) external nonReentrant { _openFarm(amount, msg.sender); }
15,348,509
[ 1, 8185, 635, 4501, 26595, 4098, 2893, 358, 443, 1724, 3675, 1351, 291, 91, 438, 670, 3665, 54, 17, 9793, 45, 2430, 358, 326, 6835, 2597, 4533, 326, 783, 11013, 471, 326, 21351, 284, 4610, 310, 11013, 225, 1922, 1375, 438, 683, 84, 841, 12, 32, 74, 4610, 6835, 20401, 3844, 22025, 4260, 358, 506, 2566, 6432, 358, 1375, 3190, 42, 4610, 68, 225, 3844, 16811, 434, 2845, 1147, 358, 506, 384, 9477, 1368, 326, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1696, 42, 4610, 12, 11890, 5034, 3844, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 389, 3190, 42, 4610, 12, 8949, 16, 1234, 18, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; import "./SafeMath.sol"; import "./TST20Interface.sol"; import "./PermissionGroups.sol"; contract TransToken is PermissionGroups { using SafeMath for uint; TST20 public MyToken; uint constant public decimals = 18; uint public minTransValue = 1*10**decimals; // 1 Token uint public transFee = 20*10**decimals; // 20 Token address public adminWithdrawAddress; event TT(uint t, address indexed addrFrom,address addrTo, uint amount, uint fee); // user operation // 1 - transfer token /* init address */ function initAddressSettings(uint _type,address _addr) onlyAdmin public { require(_addr != address(0)); if (_type == 1) { adminWithdrawAddress = _addr; }else if (_type == 2 ) { MyToken = TST20(_addr); } } /* withdraw TTC by admin */ function withdrawTTC() onlyAdmin public { require(adminWithdrawAddress.send(this.balance)); } /* withdraw Token by admin */ function withdrawToken() onlyAdmin public { MyToken.transfer(adminWithdrawAddress, MyToken.balanceOf(this)); } function setMinTransValue(uint _value) onlyAdmin public { minTransValue = _value; } function setTransFee(uint _value) onlyAdmin public { transFee = _value; } /* add sell order, amount(wei) */ function transferToken(address _target,uint _amount) public { require(_amount >= minTransValue); require(_target != address(0)); require(MyToken.balanceOf(msg.sender) >= _amount.add(transFee)); MyToken.transferFrom(msg.sender, _target, _amount); MyToken.transferFrom(msg.sender, this, transFee); TT(1, msg.sender, _target,_amount,transFee); } }
withdraw TTC by admin */
function withdrawTTC() onlyAdmin public { require(adminWithdrawAddress.send(this.balance)); }
5,355,764
[ 1, 1918, 9446, 399, 15988, 635, 3981, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1470, 39, 1435, 1338, 4446, 1071, 288, 203, 3639, 2583, 12, 3666, 1190, 9446, 1887, 18, 4661, 12, 2211, 18, 12296, 10019, 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 ]
pragma solidity ^0.4.21; // Using this contract to deploy many ballot as you want contract BallotFactory { uint public costPerBallot; // you must pay "costPerBallot" ether to create new ballot address public owner; address[] public deployedBallots; constructor (uint _costPerBallot) public payable { owner = msg.sender; costPerBallot = _costPerBallot * 1 ether; } function createBallot ( string _description, uint[] candidateIds, bytes32[] candidateNames, bytes32[] imgHashHead, bytes32[] imgHashTail, uint tokens, uint pricePerToken, uint _voteTime ) public payable returns (address) { require(msg.value >= costPerBallot, "You do not give enough money to create one ballot"); address newBallot = new Ballot(_description, candidateIds, candidateNames, imgHashHead, imgHashTail, tokens, pricePerToken, _voteTime, msg.sender); deployedBallots.push(newBallot); return newBallot; } function getDeployedBallots() public view returns (address[]) { return deployedBallots; } function getBalance() public view returns (uint) { return this.balance; } function withdraw () public { require(msg.sender == owner, "only owner can do this"); owner.transfer(this.balance); } } contract Ballot { // This is a type for a single voter struct voter { uint tokensBought; // The total no. of tokens this voter bought uint availableTokens; // Tokens that voter can use to vote bool[] tokensUsedPerCandidate; // Array to keep track candidates this voter voted. } // This is a type for a single candidate struct candidate { uint id; bytes32 name; // Short name (up to 32 bytes) bytes32 imgHashHead; // first half of image ipfs hash bytes32 imgHashTail; // second half of image ipfs hash uint voteCount; // Number of accumulated votes } address public owner; // creator of this ballot string public description; // Description for this ballot candidate[] public candidateList; // List of candidates uint public totalTokens; // Total no. of tokens available for this election uint public balanceTokens; // Total no. of tokens still available for purchase uint public tokenPrice; // Price per token uint public startTime; uint public voteTime; // After this amount of second, ballot is close /// MAPPING mapping (address => voter) public voters; function voterDetails(address voter) public view returns(uint, uint, bool[]){ return (voters[voter].tokensBought, voters[voter].availableTokens, voters[voter].tokensUsedPerCandidate); } /// MODIFIER modifier onlyOwner(){ require(msg.sender == owner, "Only owner can do this"); _; } modifier availableTime(){ require(now < startTime + voteTime, "Voting time is over"); _; } ///CONSTRUCTOR constructor ( string _description, uint[] candidateIds, bytes32[] candidateNames, bytes32[] imgHashHead, bytes32[] imgHashTail, uint tokens, uint pricePerToken, uint _voteTime, address _owner) public payable { require(candidateNames.length == candidateIds.length, "Number of name must equals number of id"); require(imgHashHead.length == candidateIds.length, "Number of images must equals number of id"); require(imgHashTail.length == candidateIds.length, "Number of images must equals number of id"); owner = _owner; description = _description; totalTokens = tokens; balanceTokens = tokens; tokenPrice = pricePerToken; startTime = now; voteTime = _voteTime; for(uint i = 0; i < candidateNames.length; i ++ ){ candidateList.push(candidate({ id: candidateIds[i], name: candidateNames[i], imgHashHead: imgHashHead[i], imgHashTail: imgHashTail[i], voteCount: 0 })); } } /// MAIN FUNCTION // Voter must buy tokens to vote. // They can vote for many candidates as they want, 1 token per candidate. function buy() public payable availableTime returns (uint) { uint tokensToBuy = msg.value / tokenPrice; //Can not buy more than balance tokens. require(tokensToBuy <= balanceTokens, "Available tokens is not enough for you"); //update ballot tokens, voter tokens voters[msg.sender].tokensBought += tokensToBuy; voters[msg.sender].availableTokens += tokensToBuy; balanceTokens -= tokensToBuy; //For one candidate, maximum tokens a voter can vote is 1. //So, maximum tokens voter can buy is number of candidates. //If there are 9 candidates, maximum tokens voter could buy is 9. require(voters[msg.sender].tokensBought <= candidateList.length, "You can not buy more tokens"); //Initiate arrar tokensUsedPerCandidate if (voters[msg.sender].tokensUsedPerCandidate.length == 0){ for(uint i = 0; i < candidateList.length; i++){ voters[msg.sender].tokensUsedPerCandidate.push(false); } } return tokensToBuy; } // Vote for candidate with id "_id" function voteForCandidate(uint _id) public availableTime { // Using id to find index of candidate // Because we can not directly find candidate by id uint index = indexOfCandidate(_id); require (index != uint(-1), "this id is not valid"); // Require this voter has enough tokens to cast the vote require (voters[msg.sender].availableTokens >= 1, "You do not have token."); // Require this voter was not vote for this candidate yet. require(voters[msg.sender].tokensUsedPerCandidate[index] == false, "You already vote for this candidate"); // Update tokens of this voter voters[msg.sender].availableTokens -= 1; voters[msg.sender].tokensUsedPerCandidate[index] = true; // Update voteCount of candidate candidateList[index].voteCount += 1; } function tokensSold() public view returns (uint) { return totalTokens - balanceTokens; } function numberCandidates() public view returns (uint) { return candidateList.length; } function getBalance() public view returns (uint) { return this.balance; } // Ballot creation can withdraw money when ballot close function withdraw() public onlyOwner { require(now >= startTime + voteTime, "Voting time is not over"); owner.transfer(this.balance); } /// HELPER FUNCTION // Get index of candidate by id function indexOfCandidate(uint _id) private view returns (uint) { for(uint i = 0; i < candidateList.length; i++) { if (candidateList[i].id == _id) { return i; } } return uint(-1); } function isOpen() public view returns (bool) { return now < startTime + voteTime; } }
HELPER FUNCTION Get index of candidate by id
function indexOfCandidate(uint _id) private view returns (uint) { for(uint i = 0; i < candidateList.length; i++) { if (candidateList[i].id == _id) { return i; } } return uint(-1); }
12,549,877
[ 1, 20264, 3194, 13690, 968, 770, 434, 5500, 635, 612, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3133, 11910, 12, 11890, 389, 350, 13, 3238, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 5500, 682, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 19188, 682, 63, 77, 8009, 350, 422, 389, 350, 13, 288, 203, 7734, 327, 277, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 2254, 19236, 21, 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 ]
// hevm: flattened sources of src/DssSpell.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.6.12 >=0.5.12 >=0.6.12 <0.7.0; ////// lib/dss-exec-lib/src/CollateralOpts.sol /* pragma solidity ^0.6.12; */ struct CollateralOpts { bytes32 ilk; address gem; address join; address clip; address calc; address pip; bool isLiquidatable; bool isOSM; bool whitelistOSM; uint256 ilkDebtCeiling; uint256 minVaultAmount; uint256 maxLiquidationAmount; uint256 liquidationPenalty; uint256 ilkStabilityFee; uint256 startingPriceFactor; uint256 breakerTolerance; uint256 auctionDuration; uint256 permittedDrop; uint256 liquidationRatio; uint256 kprFlatReward; uint256 kprPctReward; } ////// lib/dss-exec-lib/src/DssExecLib.sol // // DssExecLib.sol -- MakerDAO Executive Spellcrafting Library // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ /* import { CollateralOpts } from "./CollateralOpts.sol"; */ interface Initializable { function init(bytes32) external; } interface Authorizable { function rely(address) external; function deny(address) external; } interface Fileable { function file(bytes32, address) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, address) external; } interface Drippable { function drip() external returns (uint256); function drip(bytes32) external returns (uint256); } interface Pricing { function poke(bytes32) external; } interface ERC20 { function decimals() external returns (uint8); } interface DssVat { function hope(address) external; function nope(address) external; function ilks(bytes32) external returns (uint256 Art, uint256 rate, uint256 spot, uint256 line, uint256 dust); function Line() external view returns (uint256); function suck(address, address, uint) external; } interface ClipLike { function vat() external returns (address); function dog() external returns (address); function spotter() external view returns (address); function calc() external view returns (address); function ilk() external returns (bytes32); } interface JoinLike { function vat() external returns (address); function ilk() external returns (bytes32); function gem() external returns (address); function dec() external returns (uint256); function join(address, uint) external; function exit(address, uint) external; } // Includes Median and OSM functions interface OracleLike_2 { function src() external view returns (address); function lift(address[] calldata) external; function drop(address[] calldata) external; function setBar(uint256) external; function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; function orb0() external view returns (address); function orb1() external view returns (address); } interface MomLike { function setOsm(bytes32, address) external; function setPriceTolerance(address, uint256) external; } interface RegistryLike { function add(address) external; function xlip(bytes32) external view returns (address); } // https://github.com/makerdao/dss-chain-log interface ChainlogLike { function setVersion(string calldata) external; function setIPFS(string calldata) external; function setSha256sum(string calldata) external; function getAddress(bytes32) external view returns (address); function setAddress(bytes32, address) external; function removeAddress(bytes32) external; } interface IAMLike { function ilks(bytes32) external view returns (uint256,uint256,uint48,uint48,uint48); function setIlk(bytes32,uint256,uint256,uint256) external; function remIlk(bytes32) external; function exec(bytes32) external returns (uint256); } interface LerpFactoryLike { function newLerp(bytes32 name_, address target_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address); function newIlkLerp(bytes32 name_, address target_, bytes32 ilk_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address); } interface LerpLike { function tick() external; } library DssExecLib { /*****************/ /*** Constants ***/ /*****************/ address constant public LOG = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F; uint256 constant internal WAD = 10 ** 18; uint256 constant internal RAY = 10 ** 27; uint256 constant internal RAD = 10 ** 45; uint256 constant internal THOUSAND = 10 ** 3; uint256 constant internal MILLION = 10 ** 6; uint256 constant internal BPS_ONE_PCT = 100; uint256 constant internal BPS_ONE_HUNDRED_PCT = 100 * BPS_ONE_PCT; uint256 constant internal RATES_ONE_HUNDRED_PCT = 1000000021979553151239153027; /**********************/ /*** Math Functions ***/ /**********************/ function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } /****************************/ /*** Core Address Helpers ***/ /****************************/ function dai() public view returns (address) { return getChangelogAddress("MCD_DAI"); } function mkr() public view returns (address) { return getChangelogAddress("MCD_GOV"); } function vat() public view returns (address) { return getChangelogAddress("MCD_VAT"); } function cat() public view returns (address) { return getChangelogAddress("MCD_CAT"); } function dog() public view returns (address) { return getChangelogAddress("MCD_DOG"); } function jug() public view returns (address) { return getChangelogAddress("MCD_JUG"); } function pot() public view returns (address) { return getChangelogAddress("MCD_POT"); } function vow() public view returns (address) { return getChangelogAddress("MCD_VOW"); } function end() public view returns (address) { return getChangelogAddress("MCD_END"); } function esm() public view returns (address) { return getChangelogAddress("MCD_ESM"); } function reg() public view returns (address) { return getChangelogAddress("ILK_REGISTRY"); } function spotter() public view returns (address) { return getChangelogAddress("MCD_SPOT"); } function flap() public view returns (address) { return getChangelogAddress("MCD_FLAP"); } function flop() public view returns (address) { return getChangelogAddress("MCD_FLOP"); } function osmMom() public view returns (address) { return getChangelogAddress("OSM_MOM"); } function govGuard() public view returns (address) { return getChangelogAddress("GOV_GUARD"); } function flipperMom() public view returns (address) { return getChangelogAddress("FLIPPER_MOM"); } function clipperMom() public view returns (address) { return getChangelogAddress("CLIPPER_MOM"); } function pauseProxy() public view returns (address) { return getChangelogAddress("MCD_PAUSE_PROXY"); } function autoLine() public view returns (address) { return getChangelogAddress("MCD_IAM_AUTO_LINE"); } function daiJoin() public view returns (address) { return getChangelogAddress("MCD_JOIN_DAI"); } function lerpFab() public view returns (address) { return getChangelogAddress("LERP_FAB"); } function clip(bytes32 _ilk) public view returns (address _clip) { _clip = RegistryLike(reg()).xlip(_ilk); } function flip(bytes32 _ilk) public view returns (address _flip) { _flip = RegistryLike(reg()).xlip(_ilk); } function calc(bytes32 _ilk) public view returns (address _calc) { _calc = ClipLike(clip(_ilk)).calc(); } function getChangelogAddress(bytes32 _key) public view returns (address) { return ChainlogLike(LOG).getAddress(_key); } /****************************/ /*** Changelog Management ***/ /****************************/ /** @dev Set an address in the MCD on-chain changelog. @param _key Access key for the address (e.g. "MCD_VAT") @param _val The address associated with the _key */ function setChangelogAddress(bytes32 _key, address _val) public { ChainlogLike(LOG).setAddress(_key, _val); } /** @dev Set version in the MCD on-chain changelog. @param _version Changelog version (e.g. "1.1.2") */ function setChangelogVersion(string memory _version) public { ChainlogLike(LOG).setVersion(_version); } /** @dev Set IPFS hash of IPFS changelog in MCD on-chain changelog. @param _ipfsHash IPFS hash (e.g. "QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW") */ function setChangelogIPFS(string memory _ipfsHash) public { ChainlogLike(LOG).setIPFS(_ipfsHash); } /** @dev Set SHA256 hash in MCD on-chain changelog. @param _SHA256Sum SHA256 hash (e.g. "e42dc9d043a57705f3f097099e6b2de4230bca9a020c797508da079f9079e35b") */ function setChangelogSHA256(string memory _SHA256Sum) public { ChainlogLike(LOG).setSha256sum(_SHA256Sum); } /**********************/ /*** Authorizations ***/ /**********************/ /** @dev Give an address authorization to perform auth actions on the contract. @param _base The address of the contract where the authorization will be set @param _ward Address to be authorized */ function authorize(address _base, address _ward) public { Authorizable(_base).rely(_ward); } /** @dev Revoke contract authorization from an address. @param _base The address of the contract where the authorization will be revoked @param _ward Address to be deauthorized */ function deauthorize(address _base, address _ward) public { Authorizable(_base).deny(_ward); } /** @dev Delegate vat authority to the specified address. @param _usr Address to be authorized */ function delegateVat(address _usr) public { DssVat(vat()).hope(_usr); } /** @dev Revoke vat authority to the specified address. @param _usr Address to be deauthorized */ function undelegateVat(address _usr) public { DssVat(vat()).nope(_usr); } /******************************/ /*** OfficeHours Management ***/ /******************************/ /** @dev Returns true if a time is within office hours range @param _ts The timestamp to check, usually block.timestamp @param _officeHours true if office hours is enabled. @return true if time is in castable range */ function canCast(uint40 _ts, bool _officeHours) public pure returns (bool) { if (_officeHours) { uint256 day = (_ts / 1 days + 3) % 7; if (day >= 5) { return false; } // Can only be cast on a weekday uint256 hour = _ts / 1 hours % 24; if (hour < 14 || hour >= 21) { return false; } // Outside office hours } return true; } /** @dev Calculate the next available cast time in epoch seconds @param _eta The scheduled time of the spell plus the pause delay @param _ts The current timestamp, usually block.timestamp @param _officeHours true if office hours is enabled. @return castTime The next available cast timestamp */ function nextCastTime(uint40 _eta, uint40 _ts, bool _officeHours) public pure returns (uint256 castTime) { require(_eta != 0); // "DssExecLib/invalid eta" require(_ts != 0); // "DssExecLib/invalid ts" castTime = _ts > _eta ? _ts : _eta; // Any day at XX:YY if (_officeHours) { uint256 day = (castTime / 1 days + 3) % 7; uint256 hour = castTime / 1 hours % 24; uint256 minute = castTime / 1 minutes % 60; uint256 second = castTime % 60; if (day >= 5) { castTime += (6 - day) * 1 days; // Go to Sunday XX:YY castTime += (24 - hour + 14) * 1 hours; // Go to 14:YY UTC Monday castTime -= minute * 1 minutes + second; // Go to 14:00 UTC } else { if (hour >= 21) { if (day == 4) castTime += 2 days; // If Friday, fast forward to Sunday XX:YY castTime += (24 - hour + 14) * 1 hours; // Go to 14:YY UTC next day castTime -= minute * 1 minutes + second; // Go to 14:00 UTC } else if (hour < 14) { castTime += (14 - hour) * 1 hours; // Go to 14:YY UTC same day castTime -= minute * 1 minutes + second; // Go to 14:00 UTC } } } } /**************************/ /*** Accumulating Rates ***/ /**************************/ /** @dev Update rate accumulation for the Dai Savings Rate (DSR). */ function accumulateDSR() public { Drippable(pot()).drip(); } /** @dev Update rate accumulation for the stability fees of a given collateral type. @param _ilk Collateral type */ function accumulateCollateralStabilityFees(bytes32 _ilk) public { Drippable(jug()).drip(_ilk); } /*********************/ /*** Price Updates ***/ /*********************/ /** @dev Update price of a given collateral type. @param _ilk Collateral type */ function updateCollateralPrice(bytes32 _ilk) public { Pricing(spotter()).poke(_ilk); } /****************************/ /*** System Configuration ***/ /****************************/ /** @dev Set a contract in another contract, defining the relationship (ex. set a new Calc contract in Clip) @param _base The address of the contract where the new contract address will be filed @param _what Name of contract to file @param _addr Address of contract to file */ function setContract(address _base, bytes32 _what, address _addr) public { Fileable(_base).file(_what, _addr); } /** @dev Set a contract in another contract, defining the relationship (ex. set a new Calc contract in a Clip) @param _base The address of the contract where the new contract address will be filed @param _ilk Collateral type @param _what Name of contract to file @param _addr Address of contract to file */ function setContract(address _base, bytes32 _ilk, bytes32 _what, address _addr) public { Fileable(_base).file(_ilk, _what, _addr); } /** @dev Set a value in a contract, via a governance authorized File pattern. @param _base The address of the contract where the new contract address will be filed @param _what Name of tag for the value (e.x. "Line") @param _amt The value to set or update */ function setValue(address _base, bytes32 _what, uint256 _amt) public { Fileable(_base).file(_what, _amt); } /** @dev Set an ilk-specific value in a contract, via a governance authorized File pattern. @param _base The address of the contract where the new value will be filed @param _ilk Collateral type @param _what Name of tag for the value (e.x. "Line") @param _amt The value to set or update */ function setValue(address _base, bytes32 _ilk, bytes32 _what, uint256 _amt) public { Fileable(_base).file(_ilk, _what, _amt); } /******************************/ /*** System Risk Parameters ***/ /******************************/ // function setGlobalDebtCeiling(uint256 _amount) public { setGlobalDebtCeiling(vat(), _amount); } /** @dev Set the global debt ceiling. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setGlobalDebtCeiling(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-global-Line-precision" setValue(vat(), "Line", _amount * RAD); } /** @dev Increase the global debt ceiling by a specific amount. Amount will be converted to the correct internal precision. @param _amount The amount to add in DAI (ex. 10m DAI amount == 10000000) */ function increaseGlobalDebtCeiling(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-Line-increase-precision" address _vat = vat(); setValue(_vat, "Line", add(DssVat(_vat).Line(), _amount * RAD)); } /** @dev Decrease the global debt ceiling by a specific amount. Amount will be converted to the correct internal precision. @param _amount The amount to reduce in DAI (ex. 10m DAI amount == 10000000) */ function decreaseGlobalDebtCeiling(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-Line-decrease-precision" address _vat = vat(); setValue(_vat, "Line", sub(DssVat(_vat).Line(), _amount * RAD)); } /** @dev Set the Dai Savings Rate. See: docs/rates.txt @param _rate The accumulated rate (ex. 4% => 1000000001243680656318820312) @param _doDrip `true` to accumulate interest owed */ function setDSR(uint256 _rate, bool _doDrip) public { require((_rate >= RAY) && (_rate <= RATES_ONE_HUNDRED_PCT)); // "LibDssExec/dsr-out-of-bounds" if (_doDrip) Drippable(pot()).drip(); setValue(pot(), "dsr", _rate); } /** @dev Set the DAI amount for system surplus auctions. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setSurplusAuctionAmount(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-vow-bump-precision" setValue(vow(), "bump", _amount * RAD); } /** @dev Set the DAI amount for system surplus buffer, must be exceeded before surplus auctions start. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setSurplusBuffer(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-vow-hump-precision" setValue(vow(), "hump", _amount * RAD); } /** @dev Set minimum bid increase for surplus auctions. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setMinSurplusAuctionBidIncrease(uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-flap-beg-precision" setValue(flap(), "beg", add(WAD, wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT))); } /** @dev Set bid duration for surplus auctions. @param _duration Amount of time for bids. (in seconds) */ function setSurplusAuctionBidDuration(uint256 _duration) public { setValue(flap(), "ttl", _duration); } /** @dev Set total auction duration for surplus auctions. @param _duration Amount of time for auctions. (in seconds) */ function setSurplusAuctionDuration(uint256 _duration) public { setValue(flap(), "tau", _duration); } /** @dev Set the number of seconds that pass before system debt is auctioned for MKR tokens. @param _duration Duration in seconds */ function setDebtAuctionDelay(uint256 _duration) public { setValue(vow(), "wait", _duration); } /** @dev Set the DAI amount for system debt to be covered by each debt auction. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setDebtAuctionDAIAmount(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-vow-sump-precision" setValue(vow(), "sump", _amount * RAD); } /** @dev Set the starting MKR amount to be auctioned off to cover system debt in debt auctions. Amount will be converted to the correct internal precision. @param _amount The amount to set in MKR (ex. 250 MKR amount == 250) */ function setDebtAuctionMKRAmount(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-vow-dump-precision" setValue(vow(), "dump", _amount * WAD); } /** @dev Set minimum bid increase for debt auctions. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setMinDebtAuctionBidIncrease(uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-flap-beg-precision" setValue(flop(), "beg", add(WAD, wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT))); } /** @dev Set bid duration for debt auctions. @param _duration Amount of time for bids. */ function setDebtAuctionBidDuration(uint256 _duration) public { setValue(flop(), "ttl", _duration); } /** @dev Set total auction duration for debt auctions. @param _duration Amount of time for auctions. */ function setDebtAuctionDuration(uint256 _duration) public { setValue(flop(), "tau", _duration); } /** @dev Set the rate of increasing amount of MKR out for auction during debt auctions. Amount will be converted to the correct internal precision. @dev MKR amount is increased by this rate every "tick" (if auction duration has passed and no one has bid on the MKR) @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setDebtAuctionMKRIncreaseRate(uint256 _pct_bps) public { setValue(flop(), "pad", add(WAD, wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT))); } /** @dev Set the maximum total DAI amount that can be out for liquidation in the system at any point. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 250,000 DAI amount == 250000) */ function setMaxTotalDAILiquidationAmount(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-dog-Hole-precision" setValue(dog(), "Hole", _amount * RAD); } /** @dev (LIQ 1.2) Set the maximum total DAI amount that can be out for liquidation in the system at any point. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 250,000 DAI amount == 250000) */ function setMaxTotalDAILiquidationAmountLEGACY(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-cat-box-amount" setValue(cat(), "box", _amount * RAD); } /** @dev Set the duration of time that has to pass during emergency shutdown before collateral can start being claimed by DAI holders. @param _duration Time in seconds to set for ES processing time */ function setEmergencyShutdownProcessingTime(uint256 _duration) public { setValue(end(), "wait", _duration); } /** @dev Set the global stability fee (is not typically used, currently is 0). Many of the settings that change weekly rely on the rate accumulator described at https://docs.makerdao.com/smart-contract-modules/rates-module To check this yourself, use the following rate calculation (example 8%): $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' A table of rates can also be found at: https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW @param _rate The accumulated rate (ex. 4% => 1000000001243680656318820312) */ function setGlobalStabilityFee(uint256 _rate) public { require((_rate >= RAY) && (_rate <= RATES_ONE_HUNDRED_PCT)); // "LibDssExec/global-stability-fee-out-of-bounds" setValue(jug(), "base", _rate); } /** @dev Set the value of DAI in the reference asset (e.g. $1 per DAI). Value will be converted to the correct internal precision. @dev Equation used for conversion is value * RAY / 1000 @param _value The value to set as integer (x1000) (ex. $1.025 == 1025) */ function setDAIReferenceValue(uint256 _value) public { require(_value < WAD); // "LibDssExec/incorrect-par-precision" setValue(spotter(), "par", rdiv(_value, 1000)); } /*****************************/ /*** Collateral Management ***/ /*****************************/ /** @dev Set a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setIlkDebtCeiling(bytes32 _ilk, uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-line-precision" setValue(vat(), _ilk, "line", _amount * RAD); } /** @dev Increase a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to increase in DAI (ex. 10m DAI amount == 10000000) @param _global If true, increases the global debt ceiling by _amount */ function increaseIlkDebtCeiling(bytes32 _ilk, uint256 _amount, bool _global) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-line-precision" address _vat = vat(); (,,,uint256 line_,) = DssVat(_vat).ilks(_ilk); setValue(_vat, _ilk, "line", add(line_, _amount * RAD)); if (_global) { increaseGlobalDebtCeiling(_amount); } } /** @dev Decrease a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to decrease in DAI (ex. 10m DAI amount == 10000000) @param _global If true, decreases the global debt ceiling by _amount */ function decreaseIlkDebtCeiling(bytes32 _ilk, uint256 _amount, bool _global) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-line-precision" address _vat = vat(); (,,,uint256 line_,) = DssVat(_vat).ilks(_ilk); setValue(_vat, _ilk, "line", sub(line_, _amount * RAD)); if (_global) { decreaseGlobalDebtCeiling(_amount); } } /** @dev Set the parameters for an ilk in the "MCD_IAM_AUTO_LINE" auto-line @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The Maximum value (ex. 100m DAI amount == 100000000) @param _gap The amount of Dai per step (ex. 5m Dai == 5000000) @param _ttl The amount of time (in seconds) */ function setIlkAutoLineParameters(bytes32 _ilk, uint256 _amount, uint256 _gap, uint256 _ttl) public { require(_amount < WAD); // "LibDssExec/incorrect-auto-line-amount-precision" require(_gap < WAD); // "LibDssExec/incorrect-auto-line-gap-precision" IAMLike(autoLine()).setIlk(_ilk, _amount * RAD, _gap * RAD, _ttl); } /** @dev Set the debt ceiling for an ilk in the "MCD_IAM_AUTO_LINE" auto-line without updating the time values @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The Maximum value (ex. 100m DAI amount == 100000000) */ function setIlkAutoLineDebtCeiling(bytes32 _ilk, uint256 _amount) public { address _autoLine = autoLine(); (, uint256 gap, uint48 ttl,,) = IAMLike(_autoLine).ilks(_ilk); require(gap != 0 && ttl != 0); // "LibDssExec/auto-line-not-configured" IAMLike(_autoLine).setIlk(_ilk, _amount * RAD, uint256(gap), uint256(ttl)); } /** @dev Remove an ilk in the "MCD_IAM_AUTO_LINE" auto-line @param _ilk The ilk to remove (ex. bytes32("ETH-A")) */ function removeIlkFromAutoLine(bytes32 _ilk) public { IAMLike(autoLine()).remIlk(_ilk); } /** @dev Set a collateral minimum vault amount. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setIlkMinVaultAmount(bytes32 _ilk, uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-dust-precision" setValue(vat(), _ilk, "dust", _amount * RAD); (bool ok,) = clip(_ilk).call(abi.encodeWithSignature("upchost()")); ok; } /** @dev Set a collateral liquidation penalty. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 10.25% = 10.25 * 100 = 1025) */ function setIlkLiquidationPenalty(bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-ilk-chop-precision" setValue(dog(), _ilk, "chop", add(WAD, wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT))); (bool ok,) = clip(_ilk).call(abi.encodeWithSignature("upchost()")); ok; } /** @dev Set max DAI amount for liquidation per vault for collateral. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setIlkMaxLiquidationAmount(bytes32 _ilk, uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-hole-precision" setValue(dog(), _ilk, "hole", _amount * RAD); } /** @dev Set a collateral liquidation ratio. Amount will be converted to the correct internal precision. @dev Equation used for conversion is pct * RAY / 10,000 @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 150% = 150 * 100 = 15000) */ function setIlkLiquidationRatio(bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < 10 * BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-ilk-mat-precision" // Fails if pct >= 1000% require(_pct_bps >= BPS_ONE_HUNDRED_PCT); // the liquidation ratio has to be bigger or equal to 100% setValue(spotter(), _ilk, "mat", rdiv(_pct_bps, BPS_ONE_HUNDRED_PCT)); } /** @dev Set an auction starting multiplier. Amount will be converted to the correct internal precision. @dev Equation used for conversion is pct * RAY / 10,000 @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 1.3x starting multiplier = 130% = 13000) */ function setStartingPriceMultiplicativeFactor(bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < 10 * BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-ilk-mat-precision" // Fails if gt 10x require(_pct_bps >= BPS_ONE_HUNDRED_PCT); // fail if start price is less than OSM price setValue(clip(_ilk), "buf", rdiv(_pct_bps, BPS_ONE_HUNDRED_PCT)); } /** @dev Set the amout of time before an auction resets. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _duration Amount of time before auction resets (in seconds). */ function setAuctionTimeBeforeReset(bytes32 _ilk, uint256 _duration) public { setValue(clip(_ilk), "tail", _duration); } /** @dev Percentage drop permitted before auction reset @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, of drop to permit (x100). */ function setAuctionPermittedDrop(bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-clip-cusp-value" setValue(clip(_ilk), "cusp", rdiv(_pct_bps, BPS_ONE_HUNDRED_PCT)); } /** @dev Percentage of tab to suck from vow to incentivize keepers. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, of the tab to suck. (0.01% == 1) */ function setKeeperIncentivePercent(bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-clip-chip-precision" setValue(clip(_ilk), "chip", wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT)); } /** @dev Set max DAI amount for flat rate keeper incentive. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 1000 DAI amount == 1000) */ function setKeeperIncentiveFlatRate(bytes32 _ilk, uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-clip-tip-precision" setValue(clip(_ilk), "tip", _amount * RAD); } /** @dev Sets the circuit breaker price tolerance in the clipper mom. This is somewhat counter-intuitive, to accept a 25% price drop, use a value of 75% @param _clip The clipper to set the tolerance for @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setLiquidationBreakerPriceTolerance(address _clip, uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-clippermom-price-tolerance" MomLike(clipperMom()).setPriceTolerance(_clip, rdiv(_pct_bps, BPS_ONE_HUNDRED_PCT)); } /** @dev Set the stability fee for a given ilk. Many of the settings that change weekly rely on the rate accumulator described at https://docs.makerdao.com/smart-contract-modules/rates-module To check this yourself, use the following rate calculation (example 8%): $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' A table of rates can also be found at: https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW @param _ilk The ilk to update (ex. bytes32("ETH-A") ) @param _rate The accumulated rate (ex. 4% => 1000000001243680656318820312) @param _doDrip `true` to accumulate stability fees for the collateral */ function setIlkStabilityFee(bytes32 _ilk, uint256 _rate, bool _doDrip) public { require((_rate >= RAY) && (_rate <= RATES_ONE_HUNDRED_PCT)); // "LibDssExec/ilk-stability-fee-out-of-bounds" address _jug = jug(); if (_doDrip) Drippable(_jug).drip(_ilk); setValue(_jug, _ilk, "duty", _rate); } /*************************/ /*** Abacus Management ***/ /*************************/ /** @dev Set the number of seconds from the start when the auction reaches zero price. @dev Abacus:LinearDecrease only. @param _calc The address of the LinearDecrease pricing contract @param _duration Amount of time for auctions. */ function setLinearDecrease(address _calc, uint256 _duration) public { setValue(_calc, "tau", _duration); } /** @dev Set the number of seconds for each price step. @dev Abacus:StairstepExponentialDecrease only. @param _calc The address of the StairstepExponentialDecrease pricing contract @param _duration Length of time between price drops [seconds] @param _pct_bps Per-step multiplicative factor in basis points. (ex. 99% == 9900) */ function setStairstepExponentialDecrease(address _calc, uint256 _duration, uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // DssExecLib/cut-too-high setValue(_calc, "cut", rdiv(_pct_bps, BPS_ONE_HUNDRED_PCT)); setValue(_calc, "step", _duration); } /** @dev Set the number of seconds for each price step. (99% cut = 1% price drop per step) Amounts will be converted to the correct internal precision. @dev Abacus:ExponentialDecrease only @param _calc The address of the ExponentialDecrease pricing contract @param _pct_bps Per-step multiplicative factor in basis points. (ex. 99% == 9900) */ function setExponentialDecrease(address _calc, uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // DssExecLib/cut-too-high setValue(_calc, "cut", rdiv(_pct_bps, BPS_ONE_HUNDRED_PCT)); } /*************************/ /*** Oracle Management ***/ /*************************/ /** @dev Allows an oracle to read prices from its source feeds @param _oracle An OSM or LP oracle contract */ function whitelistOracleMedians(address _oracle) public { (bool ok, bytes memory data) = _oracle.call(abi.encodeWithSignature("orb0()")); if (ok) { // Token is an LP oracle address median0 = abi.decode(data, (address)); addReaderToMedianWhitelist(median0, _oracle); addReaderToMedianWhitelist(OracleLike_2(_oracle).orb1(), _oracle); } else { // Standard OSM addReaderToMedianWhitelist(OracleLike_2(_oracle).src(), _oracle); } } /** @dev Adds oracle feeds to the Median's writer whitelist, allowing the feeds to write prices. @param _median Median core contract address @param _feeds Array of oracle feed addresses to add to whitelist */ function addWritersToMedianWhitelist(address _median, address[] memory _feeds) public { OracleLike_2(_median).lift(_feeds); } /** @dev Removes oracle feeds to the Median's writer whitelist, disallowing the feeds to write prices. @param _median Median core contract address @param _feeds Array of oracle feed addresses to remove from whitelist */ function removeWritersFromMedianWhitelist(address _median, address[] memory _feeds) public { OracleLike_2(_median).drop(_feeds); } /** @dev Adds addresses to the Median's reader whitelist, allowing the addresses to read prices from the median. @param _median Median core contract address @param _readers Array of addresses to add to whitelist */ function addReadersToMedianWhitelist(address _median, address[] memory _readers) public { OracleLike_2(_median).kiss(_readers); } /** @dev Adds an address to the Median's reader whitelist, allowing the address to read prices from the median. @param _median Median core contract address @param _reader Address to add to whitelist */ function addReaderToMedianWhitelist(address _median, address _reader) public { OracleLike_2(_median).kiss(_reader); } /** @dev Removes addresses from the Median's reader whitelist, disallowing the addresses to read prices from the median. @param _median Median core contract address @param _readers Array of addresses to remove from whitelist */ function removeReadersFromMedianWhitelist(address _median, address[] memory _readers) public { OracleLike_2(_median).diss(_readers); } /** @dev Removes an address to the Median's reader whitelist, disallowing the address to read prices from the median. @param _median Median core contract address @param _reader Address to remove from whitelist */ function removeReaderFromMedianWhitelist(address _median, address _reader) public { OracleLike_2(_median).diss(_reader); } /** @dev Sets the minimum number of valid messages from whitelisted oracle feeds needed to update median price. @param _median Median core contract address @param _minQuorum Minimum number of valid messages from whitelisted oracle feeds needed to update median price (NOTE: MUST BE ODD NUMBER) */ function setMedianWritersQuorum(address _median, uint256 _minQuorum) public { OracleLike_2(_median).setBar(_minQuorum); } /** @dev Adds an address to the Median's reader whitelist, allowing the address to read prices from the OSM. @param _osm Oracle Security Module (OSM) core contract address @param _reader Address to add to whitelist */ function addReaderToOSMWhitelist(address _osm, address _reader) public { OracleLike_2(_osm).kiss(_reader); } /** @dev Removes an address to the Median's reader whitelist, disallowing the address to read prices from the OSM. @param _osm Oracle Security Module (OSM) core contract address @param _reader Address to remove from whitelist */ function removeReaderFromOSMWhitelist(address _osm, address _reader) public { OracleLike_2(_osm).diss(_reader); } /** @dev Add OSM address to OSM mom, allowing it to be frozen by governance. @param _osm Oracle Security Module (OSM) core contract address @param _ilk Collateral type using OSM */ function allowOSMFreeze(address _osm, bytes32 _ilk) public { MomLike(osmMom()).setOsm(_ilk, _osm); } /*****************************/ /*** Collateral Onboarding ***/ /*****************************/ /** @dev Performs basic functions and sanity checks to add a new collateral type to the MCD system @param _ilk Collateral type key code [Ex. "ETH-A"] @param _gem Address of token contract @param _join Address of join adapter @param _clip Address of liquidation agent @param _calc Address of the pricing function @param _pip Address of price feed */ function addCollateralBase( bytes32 _ilk, address _gem, address _join, address _clip, address _calc, address _pip ) public { // Sanity checks address _vat = vat(); address _dog = dog(); address _spotter = spotter(); require(JoinLike(_join).vat() == _vat); // "join-vat-not-match" require(JoinLike(_join).ilk() == _ilk); // "join-ilk-not-match" require(JoinLike(_join).gem() == _gem); // "join-gem-not-match" require(JoinLike(_join).dec() == ERC20(_gem).decimals()); // "join-dec-not-match" require(ClipLike(_clip).vat() == _vat); // "clip-vat-not-match" require(ClipLike(_clip).dog() == _dog); // "clip-dog-not-match" require(ClipLike(_clip).ilk() == _ilk); // "clip-ilk-not-match" require(ClipLike(_clip).spotter() == _spotter); // "clip-ilk-not-match" // Set the token PIP in the Spotter setContract(spotter(), _ilk, "pip", _pip); // Set the ilk Clipper in the Dog setContract(_dog, _ilk, "clip", _clip); // Set vow in the clip setContract(_clip, "vow", vow()); // Set the pricing function for the Clipper setContract(_clip, "calc", _calc); // Init ilk in Vat & Jug Initializable(_vat).init(_ilk); // Vat Initializable(jug()).init(_ilk); // Jug // Allow ilk Join to modify Vat registry authorize(_vat, _join); // Allow ilk Join to suck dai for keepers authorize(_vat, _clip); // Allow the ilk Clipper to reduce the Dog hole on deal() authorize(_dog, _clip); // Allow Dog to kick auctions in ilk Clipper authorize(_clip, _dog); // Allow End to yank auctions in ilk Clipper authorize(_clip, end()); // Authorize the ESM to execute in the clipper authorize(_clip, esm()); // Add new ilk to the IlkRegistry RegistryLike(reg()).add(_join); } /***************/ /*** Payment ***/ /***************/ /** @dev Send a payment in ERC20 DAI from the surplus buffer. @param _target The target address to send the DAI to. @param _amount The amount to send in DAI (ex. 10m DAI amount == 10000000) */ function sendPaymentFromSurplusBuffer(address _target, uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-line-precision" DssVat(vat()).suck(vow(), address(this), _amount * RAD); JoinLike(daiJoin()).exit(_target, _amount * WAD); } /************/ /*** Misc ***/ /************/ /** @dev Initiate linear interpolation on an administrative value over time. @param _name The label for this lerp instance @param _target The target contract @param _what The target parameter to adjust @param _startTime The time for this lerp @param _start The start value for the target parameter @param _end The end value for the target parameter @param _duration The duration of the interpolation */ function linearInterpolation(bytes32 _name, address _target, bytes32 _what, uint256 _startTime, uint256 _start, uint256 _end, uint256 _duration) public returns (address) { address lerp = LerpFactoryLike(lerpFab()).newLerp(_name, _target, _what, _startTime, _start, _end, _duration); Authorizable(_target).rely(lerp); LerpLike(lerp).tick(); return lerp; } /** @dev Initiate linear interpolation on an administrative value over time. @param _name The label for this lerp instance @param _target The target contract @param _ilk The ilk to target @param _what The target parameter to adjust @param _startTime The time for this lerp @param _start The start value for the target parameter @param _end The end value for the target parameter @param _duration The duration of the interpolation */ function linearInterpolation(bytes32 _name, address _target, bytes32 _ilk, bytes32 _what, uint256 _startTime, uint256 _start, uint256 _end, uint256 _duration) public returns (address) { address lerp = LerpFactoryLike(lerpFab()).newIlkLerp(_name, _target, _ilk, _what, _startTime, _start, _end, _duration); Authorizable(_target).rely(lerp); LerpLike(lerp).tick(); return lerp; } } ////// lib/dss-exec-lib/src/DssAction.sol // // DssAction.sol -- DSS Executive Spell Actions // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ /* import { DssExecLib } from "./DssExecLib.sol"; */ /* import { CollateralOpts } from "./CollateralOpts.sol"; */ interface OracleLike_1 { function src() external view returns (address); } abstract contract DssAction { using DssExecLib for *; // Modifier used to limit execution time when office hours is enabled modifier limited { require(DssExecLib.canCast(uint40(block.timestamp), officeHours()), "Outside office hours"); _; } // Office Hours defaults to true by default. // To disable office hours, override this function and // return false in the inherited action. function officeHours() public virtual returns (bool) { return true; } // DssExec calls execute. We limit this function subject to officeHours modifier. function execute() external limited { actions(); } // DssAction developer must override `actions()` and place all actions to be called inside. // The DssExec function will call this subject to the officeHours limiter // By keeping this function public we allow simulations of `execute()` on the actions outside of the cast time. function actions() public virtual; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)" function description() external virtual view returns (string memory); // Returns the next available cast time function nextCastTime(uint256 eta) external returns (uint256 castTime) { require(eta <= uint40(-1)); castTime = DssExecLib.nextCastTime(uint40(eta), uint40(block.timestamp), officeHours()); } } ////// lib/dss-exec-lib/src/DssExec.sol // // DssExec.sol -- MakerDAO Executive Spell Template // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ interface PauseAbstract { function delay() external view returns (uint256); function plot(address, bytes32, bytes calldata, uint256) external; function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory); } interface Changelog { function getAddress(bytes32) external view returns (address); } interface SpellAction { function officeHours() external view returns (bool); function description() external view returns (string memory); function nextCastTime(uint256) external view returns (uint256); } contract DssExec { Changelog constant public log = Changelog(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F); uint256 public eta; bytes public sig; bool public done; bytes32 immutable public tag; address immutable public action; uint256 immutable public expiration; PauseAbstract immutable public pause; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)" function description() external view returns (string memory) { return SpellAction(action).description(); } function officeHours() external view returns (bool) { return SpellAction(action).officeHours(); } function nextCastTime() external view returns (uint256 castTime) { return SpellAction(action).nextCastTime(eta); } // @param _description A string description of the spell // @param _expiration The timestamp this spell will expire. (Ex. now + 30 days) // @param _spellAction The address of the spell action constructor(uint256 _expiration, address _spellAction) public { pause = PauseAbstract(log.getAddress("MCD_PAUSE")); expiration = _expiration; action = _spellAction; sig = abi.encodeWithSignature("execute()"); bytes32 _tag; // Required for assembly access address _action = _spellAction; // Required for assembly access assembly { _tag := extcodehash(_action) } tag = _tag; } function schedule() public { require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + PauseAbstract(pause).delay(); pause.plot(action, tag, sig, eta); } function cast() public { require(!done, "spell-already-cast"); done = true; pause.exec(action, tag, sig, eta); } } ////// lib/dss-interfaces/src/dss/IlkRegistryAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/ilk-registry interface IlkRegistryAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function dog() external view returns (address); function cat() external view returns (address); function spot() external view returns (address); function ilkData(bytes32) external view returns ( uint96, address, address, uint8, uint96, address, address, string memory, string memory ); function ilks() external view returns (bytes32[] memory); function ilks(uint) external view returns (bytes32); function add(address) external; function remove(bytes32) external; function update(bytes32) external; function removeAuth(bytes32) external; function file(bytes32, address) external; function file(bytes32, bytes32, address) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, string calldata) external; function count() external view returns (uint256); function list() external view returns (bytes32[] memory); function list(uint256, uint256) external view returns (bytes32[] memory); function get(uint256) external view returns (bytes32); function info(bytes32) external view returns ( string memory, string memory, uint256, uint256, address, address, address, address ); function pos(bytes32) external view returns (uint256); function class(bytes32) external view returns (uint256); function gem(bytes32) external view returns (address); function pip(bytes32) external view returns (address); function join(bytes32) external view returns (address); function xlip(bytes32) external view returns (address); function dec(bytes32) external view returns (uint256); function symbol(bytes32) external view returns (string memory); function name(bytes32) external view returns (string memory); function put(bytes32, address, address, uint256, uint256, address, address, string calldata, string calldata) external; } ////// lib/dss-interfaces/src/dss/VatAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/vat.sol interface VatAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function can(address, address) external view returns (uint256); function hope(address) external; function nope(address) external; function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function urns(bytes32, address) external view returns (uint256, uint256); function gem(bytes32, address) external view returns (uint256); function dai(address) external view returns (uint256); function sin(address) external view returns (uint256); function debt() external view returns (uint256); function vice() external view returns (uint256); function Line() external view returns (uint256); function live() external view returns (uint256); function init(bytes32) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function cage() external; function slip(bytes32, address, int256) external; function flux(bytes32, address, address, uint256) external; function move(address, address, uint256) external; function frob(bytes32, address, address, address, int256, int256) external; function fork(bytes32, address, address, int256, int256) external; function grab(bytes32, address, address, address, int256, int256) external; function heal(uint256) external; function suck(address, address, uint256) external; function fold(bytes32, address, int256) external; } ////// src/DssSpell.sol // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity 0.6.12; */ /* import "dss-exec-lib/DssExec.sol"; */ /* import "dss-exec-lib/DssAction.sol"; */ /* import "lib/dss-interfaces/src/dss/IlkRegistryAbstract.sol"; */ /* import "lib/dss-interfaces/src/dss/VatAbstract.sol"; */ contract DssSpellAction is DssAction { // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/67317d1cacd8cd2ad74b3627680631ec3edc56d6/governance/votes/Executive%20vote%20-%20August%206,%202021.md -q -O - 2>/dev/null)" string public constant override description = "2021-08-06 MakerDAO Executive Spell | Hash: 0xe64f6b5cde09dbc711b833a0adba5a2e970fafbeeee848bb7ff5b80e7b54d8d2"; // Turn off office hours function officeHours() public override returns (bool) { return false; } // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' // // A table of rates can be found at // https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW // uint256 constant FIVE_PCT = 1000000001547125957863212448; // Math uint256 constant THOUSAND = 10 ** 3; uint256 constant MILLION = 10 ** 6; uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; uint256 constant RAD = 10 ** 45; // Growth Core Unit address constant GRO_MULTISIG = 0x7800C137A645c07132886539217ce192b9F0528e; // Ses Core Unit address constant SES_MULTISIG = 0x87AcDD9208f73bFc9207e1f6F0fDE906bcA95cc6; // Content Production Core Unit address constant MKT_MULTISIG = 0xDCAF2C84e1154c8DdD3203880e5db965bfF09B60; // GovAlpha Core Unit address constant GOV_MULTISIG = 0x01D26f8c5cC009868A4BF66E268c17B057fF7A73; // Real-World Finance Core Unit address constant RWF_MULTISIG = 0x9e1585d9CA64243CE43D42f7dD7333190F66Ca09; // Risk Core Unit address constant RISK_CU_EOA = 0xd98ef20520048a35EdA9A202137847A62120d2d9; // Protocol Engineering address constant PE_MULTISIG = 0xe2c16c308b843eD02B09156388Cb240cEd58C01c; // Oracles Core Unit address constant ORA_MULTISIG = 0x2d09B7b95f3F312ba6dDfB77bA6971786c5b50Cf; // Com Core Unit (Operating) address constant COM_MULTISIG = 0x1eE3ECa7aEF17D1e74eD7C447CcBA61aC76aDbA9; // Com Core Unit (Emergency Fund) address constant COM_ER_MULTISIG = 0x99E1696A680c0D9f426Be20400E468089E7FDB0f; address public constant MAKER_CHANGELOG = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F; // Based on https://github.com/makerdao/vote-delegate/blob/master/README.md address public constant VOTE_DELEGATE_PROXY_FACTORY = 0xD897F108670903D1d6070fcf818f9db3615AF272; function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function actions() public override { address MCD_VAT = DssExecLib.vat(); // ----------- Core Unit Budget Payouts - August ----------- DssExecLib.sendPaymentFromSurplusBuffer(GRO_MULTISIG, 637_900); DssExecLib.sendPaymentFromSurplusBuffer(SES_MULTISIG, 702_883); DssExecLib.sendPaymentFromSurplusBuffer(MKT_MULTISIG, 98_067); DssExecLib.sendPaymentFromSurplusBuffer(GOV_MULTISIG, 123_333); DssExecLib.sendPaymentFromSurplusBuffer(RWF_MULTISIG, 155_000); DssExecLib.sendPaymentFromSurplusBuffer(RISK_CU_EOA, 182_000); DssExecLib.sendPaymentFromSurplusBuffer(PE_MULTISIG, 510_000); DssExecLib.sendPaymentFromSurplusBuffer(ORA_MULTISIG, 419_677); DssExecLib.sendPaymentFromSurplusBuffer(COM_MULTISIG, 40_500); DssExecLib.sendPaymentFromSurplusBuffer(COM_ER_MULTISIG, 121_500); // _________ // TOTAL DAI: 2,990,860 // ----------- Maker Open Market Commitee Proposal ----------- // https://vote.makerdao.com/polling/QmVG38FK?network=mainnet#poll-detail // ETH-B Stability Fee Decrease 6% to 5% DssExecLib.setIlkStabilityFee("ETH-B", FIVE_PCT, true); // Maximum Debt Ceiling Decreases. DssExecLib.setIlkAutoLineDebtCeiling("LRC-A", 1 * MILLION); // Decrease 3 million to 1 million. DssExecLib.removeIlkFromAutoLine("UNIV2ETHUSDT-A"); // Decrease 10 million to zero. (,,,uint256 univ2EthUsdtLine,) = VatAbstract(MCD_VAT).ilks("UNIV2ETHUSDT-A"); DssExecLib.setIlkDebtCeiling("UNIV2ETHUSDT-A", 0); // -univ2EthUsdtLine DssExecLib.removeIlkFromAutoLine("UNIV2DAIUSDT-A"); // Decrease 10 million to zero. (,,,uint256 univ2DaiUsdtLine,) = VatAbstract(MCD_VAT).ilks("UNIV2DAIUSDT-A"); DssExecLib.setIlkDebtCeiling("UNIV2DAIUSDT-A", 0); // -univ2DaiUsdtLine uint256 removed = add(univ2EthUsdtLine, univ2DaiUsdtLine); uint256 Line = VatAbstract(MCD_VAT).Line(); VatAbstract(MCD_VAT).file("Line", sub(Line, removed)); // ----------- Increase UNIV2DAUUSDC-A Maximum Debt Ceiling ----------- // https://vote.makerdao.com/polling/QmRAuMND?network=mainnet#poll-detail DssExecLib.setIlkAutoLineParameters("UNIV2DAIUSDC-A", 250 * MILLION, 10 * MILLION, 8 hours); // 50 million to 250 million. // ----------- Housekeeping ----------- // Update RWA tokens symbols in ilk registry IlkRegistryAbstract ILK_REGISTRY = IlkRegistryAbstract(DssExecLib.reg()); ILK_REGISTRY.file("RWA001-A", "symbol", "RWA001"); ILK_REGISTRY.file("RWA002-A", "symbol", "RWA002"); ILK_REGISTRY.file("RWA003-A", "symbol", "RWA003"); ILK_REGISTRY.file("RWA004-A", "symbol", "RWA004"); ILK_REGISTRY.file("RWA005-A", "symbol", "RWA005"); ILK_REGISTRY.file("RWA006-A", "symbol", "RWA006"); // Add vote delegate factory to changelog DssExecLib.setChangelogAddress("VOTE_DELEGATE_PROXY_FACTORY", VOTE_DELEGATE_PROXY_FACTORY); // Bump changelog version DssExecLib.setChangelogVersion("1.9.3"); } } contract DssSpell is DssExec { constructor() DssExec(block.timestamp + 30 days, address(new DssSpellAction())) public {} }
Content Production Core Unit
address constant MKT_MULTISIG = 0xDCAF2C84e1154c8DdD3203880e5db965bfF09B60;
1,687,465
[ 1, 1350, 10856, 349, 4586, 8380, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1758, 5381, 490, 47, 56, 67, 26588, 18513, 3639, 273, 374, 17593, 3587, 42, 22, 39, 5193, 73, 2499, 6564, 71, 28, 40, 72, 40, 1578, 4630, 28, 3672, 73, 25, 1966, 29, 9222, 17156, 42, 5908, 38, 4848, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Items. @author Tim Clancy This is the governing registry of all SuperFarm Item assets. */ contract FarmItemRecords is Ownable, ReentrancyGuard { /// A version number for this record contract's interface. uint256 public version = 1; /// A mapping for an array of all Fee1155s deployed by a particular address. mapping (address => address[]) public itemRecords; /// An event for tracking the creation of a new Item. event ItemCreated(address indexed itemAddress, address indexed creator); /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /** Construct a new item registry with a specific OpenSea proxy address. @param _proxyRegistryAddress An OpenSea proxy registry address. */ constructor(address _proxyRegistryAddress) public { proxyRegistryAddress = _proxyRegistryAddress; } /** Create a Fee1155 on behalf of the owner calling this function. The Fee1155 immediately mints a single-item collection. @param _uri The item group's metadata URI. @param _royaltyFee The creator's fee to apply to the created item. @param _initialSupply An array of per-item initial supplies which should be minted immediately. @param _maximumSupply An array of per-item maximum supplies. @param _recipients An array of addresses which will receive the initial supply minted for each corresponding item. @param _data Any associated data to use if items are minted this transaction. */ function createItem(string calldata _uri, uint256 _royaltyFee, uint256[] calldata _initialSupply, uint256[] calldata _maximumSupply, address[] calldata _recipients, bytes calldata _data) external nonReentrant returns (Fee1155) { FeeOwner royaltyFeeOwner = new FeeOwner(_royaltyFee, 30000); Fee1155 newItemGroup = new Fee1155(_uri, royaltyFeeOwner, proxyRegistryAddress); newItemGroup.create(_initialSupply, _maximumSupply, _recipients, _data); // Transfer ownership of the new Item to the user then store a reference. royaltyFeeOwner.transferOwnership(msg.sender); newItemGroup.transferOwnership(msg.sender); address itemAddress = address(newItemGroup); itemRecords[msg.sender].push(itemAddress); emit ItemCreated(itemAddress, msg.sender); return newItemGroup; } /** Allow a user to add an existing Item contract to the registry. @param _itemAddress The address of the Item contract to add for this user. */ function addItem(address _itemAddress) external { itemRecords[msg.sender].push(_itemAddress); } /** Get the number of entries in the Item records mapping for the given user. @return The number of Items added for a given address. */ function getItemCount(address _user) external view returns (uint256) { return itemRecords[_user].length; } } // 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.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: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title Represents ownership over a fee of some percentage. @author Tim Clancy */ contract FeeOwner is Ownable { using SafeMath for uint256; /// A version number for this FeeOwner contract's interface. uint256 public version = 1; /// The percent fee due to this contract's owner, represented as 1/1000th of a percent. That is, a 1% fee maps to 1000. uint256 public fee; /// The maximum configurable percent fee due to this contract's owner, represented as 1/1000th of a percent. uint256 public maximumFee; /// An event for tracking modification of the fee. event FeeChanged(uint256 oldFee, uint256 newFee); /** Construct a new FeeOwner by providing specifying a fee. @param _fee The percent fee to apply, represented as 1/1000th of a percent. @param _maximumFee The maximum possible fee that the owner can set. */ constructor(uint256 _fee, uint256 _maximumFee) public { require(_fee <= _maximumFee, "The fee cannot be set above its maximum."); fee = _fee; maximumFee = _maximumFee; } /** Allows the owner of this fee to modify what they take, within bounds. @param newFee The new fee to begin using. */ function changeFee(uint256 newFee) external onlyOwner { require(newFee <= maximumFee, "The fee cannot be set above its original maximum."); emit FeeChanged(fee, newFee); fee = newFee; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @title An ERC-1155 item creation contract which specifies an associated FeeOwner who receives royalties from sales of created items. @author Tim Clancy The fee set by the FeeOwner on this Item is honored by Shop contracts. In addition to the inherited OpenZeppelin dependency, this uses ideas from the original ERC-1155 reference implementation. */ contract Fee1155 is ERC1155, Ownable { using SafeMath for uint256; /// A version number for this fee-bearing 1155 item contract's interface. uint256 public version = 1; /// The ERC-1155 URI for looking up item metadata using {id} substitution. string public metadataUri; /// A user-specified FeeOwner to receive a portion of item sale earnings. FeeOwner public feeOwner; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A counter to enforce unique IDs for each item group minted. uint256 public nextItemGroupId; /// This mapping tracks the number of unique items within each item group. mapping (uint256 => uint256) public itemGroupSizes; /// A mapping of item IDs to their circulating supplies. mapping (uint256 => uint256) public currentSupply; /// A mapping of item IDs to their maximum supplies; true NFTs are unique. mapping (uint256 => uint256) public maximumSupply; /// A mapping of all addresses approved to mint items on behalf of the owner. mapping (address => bool) public approvedMinters; /// An event for tracking the creation of an item group. event ItemGroupCreated(uint256 itemGroupId, uint256 itemGroupSize, address indexed creator); /// A custom modifier which permits only approved minters to mint items. modifier onlyMinters { require(msg.sender == owner() || approvedMinters[msg.sender], "You are not an approved minter for this item."); _; } /** Construct a new ERC-1155 item with an associated FeeOwner fee. @param _uri The metadata URI to perform token ID substitution in. @param _feeOwner The address of a FeeOwner who receives earnings from this item. @param _proxyRegistryAddress An OpenSea proxy registry address. */ constructor(string memory _uri, FeeOwner _feeOwner, address _proxyRegistryAddress) public ERC1155(_uri) { metadataUri = _uri; feeOwner = _feeOwner; proxyRegistryAddress = _proxyRegistryAddress; nextItemGroupId = 0; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** Allow the item owner to update the metadata URI of this collection. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external onlyOwner { metadataUri = _uri; } /** Allows the owner of this contract to grant or remove approval to an external minter of items. @param _minter The external address allowed to mint items. @param _approval The updated `_minter` approval status. */ function approveMinter(address _minter, bool _approval) external onlyOwner { approvedMinters[_minter] = _approval; } /** This function creates an "item group" which may contain one or more individual items. The items within a group may be any combination of fungible or nonfungible. The distinction between a fungible and a nonfungible item is made by checking the item's possible `_maximumSupply`; nonfungible items will naturally have a maximum supply of one because they are unqiue. Creating an item through this function defines its maximum supply. The size of the item group is inferred from the size of the input arrays. The primary purpose of an item group is to create a collection of nonfungible items where each item within the collection is unique but they all share some data as a group. The primary example of this is something like a series of 100 trading cards where each card is unique with its issue number from 1 to 100 but all otherwise reflect the same metadata. In such an example, the `_maximumSupply` of each item is one and the size of the group would be specified by passing an array with 100 elements in it to this function: [ 1, 1, 1, ... 1 ]. Within an item group, items are 1-indexed with the 0-index of the item group supporting lookup of item group metadata. This 0-index metadata includes lookup via `maximumSupply` of the full count of items in the group should all of the items be minted, lookup via `currentSupply` of the number of items circulating from the group as a whole, and lookup via `groupSizes` of the number of unique items within the group. @param initialSupply An array of per-item initial supplies which should be minted immediately. @param _maximumSupply An array of per-item maximum supplies. @param recipients An array of addresses which will receive the initial supply minted for each corresponding item. @param data Any associated data to use if items are minted this transaction. */ function create(uint256[] calldata initialSupply, uint256[] calldata _maximumSupply, address[] calldata recipients, bytes calldata data) external onlyOwner returns (uint256) { uint256 groupSize = initialSupply.length; require(groupSize > 0, "You cannot create an empty item group."); require(initialSupply.length == _maximumSupply.length, "Initial supply length cannot be mismatched with maximum supply length."); require(initialSupply.length == recipients.length, "Initial supply length cannot be mismatched with recipients length."); // Create an item group of requested size using the next available ID. uint256 shiftedGroupId = nextItemGroupId << 128; itemGroupSizes[shiftedGroupId] = groupSize; emit ItemGroupCreated(shiftedGroupId, groupSize, msg.sender); // Record the supply cap of each item being created in the group. uint256 fullCollectionSize = 0; for (uint256 i = 0; i < groupSize; i++) { uint256 itemInitialSupply = initialSupply[i]; uint256 itemMaximumSupply = _maximumSupply[i]; fullCollectionSize = fullCollectionSize.add(itemMaximumSupply); require(itemMaximumSupply > 0, "You cannot create an item which is never mintable."); require(itemInitialSupply <= itemMaximumSupply, "You cannot create an item which exceeds its own supply cap."); // The item ID is offset by one because the zero index of the group is used to store the group size. uint256 itemId = shiftedGroupId.add(i + 1); maximumSupply[itemId] = itemMaximumSupply; // If this item is being initialized with a supply, mint to the recipient. if (itemInitialSupply > 0) { address itemRecipient = recipients[i]; _mint(itemRecipient, itemId, itemInitialSupply, data); currentSupply[itemId] = itemInitialSupply; } } // Also record the full size of the entire item group. maximumSupply[shiftedGroupId] = fullCollectionSize; // Increment our next item group ID and return our created item group ID. nextItemGroupId = nextItemGroupId.add(1); return shiftedGroupId; } /** Allow the item owner to mint a new item, so long as there is supply left to do so. @param to The address to send the newly-minted items to. @param id The ERC-1155 ID of the item being minted. @param amount The amount of the new item to mint. @param data Any associated data for this minting event that should be passed. */ function mint(address to, uint256 id, uint256 amount, bytes calldata data) external onlyMinters { uint256 groupId = id & GROUP_MASK; require(groupId != id, "You cannot mint an item with an issuance index of 0."); currentSupply[groupId] = currentSupply[groupId].add(amount); uint256 newSupply = currentSupply[id].add(amount); currentSupply[id] = newSupply; require(newSupply <= maximumSupply[id], "You cannot mint an item beyond its permitted maximum supply."); _mint(to, id, amount, data); } /** Allow the item owner to mint a new batch of items, so long as there is supply left to do so for each item. @param to The address to send the newly-minted items to. @param ids The ERC-1155 IDs of the items being minted. @param amounts The amounts of the new items to mint. @param data Any associated data for this minting event that should be passed. */ function mintBatch(address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external onlyMinters { require(ids.length > 0, "You cannot perform an empty mint."); require(ids.length == amounts.length, "Supplied IDs length cannot be mismatched with amounts length."); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 groupId = id & GROUP_MASK; require(groupId != id, "You cannot mint an item with an issuance index of 0."); currentSupply[groupId] = currentSupply[groupId].add(amount); uint256 newSupply = currentSupply[id].add(amount); currentSupply[id] = newSupply; require(newSupply <= maximumSupply[id], "You cannot mint an item beyond its permitted maximum supply."); } _mintBatch(to, ids, amounts, data); } } // 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 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 "./IERC1155.sol"; import "./IERC1155MetadataURI.sol"; import "./IERC1155Receiver.sol"; import "../../utils/Context.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // 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 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: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; /** @title A simple Shop contract for selling ERC-1155s for Ether via direct minting. @author Tim Clancy This contract is a limited subset of the Shop1155 contract designed to mint items directly to the user upon purchase. This shop additionally requires the owner to directly approve purchase requests from prospective buyers. */ contract ShopEtherMinter1155Curated is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 1; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A user-specified Fee1155 contract to support selling items from. Fee1155 public item; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// The Shop's inventory of item groups for sale. uint256[] public inventory; /// The Shop's price for each item group. mapping (uint256 => uint256) public prices; /// A mapping of each item group ID to an array of addresses with offers. mapping (uint256 => address[]) public bidders; /// A mapping for each item group ID to a mapping of address-price offers. mapping (uint256 => mapping (address => uint256)) public offers; /** Construct a new Shop by providing it a FeeOwner. @param _item The address of the Fee1155 item that will be minting sales. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. */ constructor(Fee1155 _item, FeeOwner _feeOwner) public { item = _item; feeOwner = _feeOwner; } /** Returns the length of the inventory array. @return the length of the inventory array. */ function getInventoryCount() external view returns (uint256) { return inventory.length; } /** Returns the length of the bidder array on an item group. @return the length of the bidder array on an item group. */ function getBidderCount(uint256 groupId) external view returns (uint256) { return bidders[groupId].length; } /** Allows the Shop owner to list a new set of NFT items for sale. @param _groupIds The item group IDs to list for sale in this shop. @param _prices The corresponding purchase price to mint an item of each group. */ function listItems(uint256[] calldata _groupIds, uint256[] calldata _prices) external onlyOwner { require(_groupIds.length > 0, "You must list at least one item."); require(_groupIds.length == _prices.length, "Items length cannot be mismatched with prices length."); // Iterate through every specified item group to list items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; uint256 price = _prices[i]; inventory.push(groupId); prices[groupId] = price; } } /** Allows the Shop owner to remove items from sale. @param _groupIds The group IDs currently listed in the shop to take off sale. */ function removeItems(uint256[] calldata _groupIds) external onlyOwner { require(_groupIds.length > 0, "You must remove at least one item."); // Iterate through every specified item group to remove items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; prices[groupId] = 0; } } /** Allows any user to place an offer to purchase an item group from this Shop. For this shop, users place an offer automatically at the price set by the Shop owner. This function takes a user's Ether into escrow for the offer. @param _itemGroupIds An array of (unique) item groups for a user to place an offer for. */ function makeOffers(uint256[] calldata _itemGroupIds) public nonReentrant payable { require(_itemGroupIds.length > 0, "You must make an offer for at least one item group."); // Iterate through every specified item to make an offer on items. for (uint256 i = 0; i < _itemGroupIds.length; i++) { uint256 groupId = _itemGroupIds[i]; uint256 price = prices[groupId]; require(price > 0, "You cannot make an offer for an item that is not listed."); // Record an offer for this item. bidders[groupId].push(msg.sender); offers[groupId][msg.sender] = msg.value; } } /** Allows any user to cancel an offer for items from this Shop. This function returns a user's Ether if there is any in escrow for the item group. @param _itemGroupIds An array of (unique) item groups for a user to cancel an offer for. */ function cancelOffers(uint256[] calldata _itemGroupIds) public nonReentrant { require(_itemGroupIds.length > 0, "You must cancel an offer for at least one item group."); // Iterate through every specified item to cancel offers on items. uint256 returnedOfferAmount = 0; for (uint256 i = 0; i < _itemGroupIds.length; i++) { uint256 groupId = _itemGroupIds[i]; uint256 offeredValue = offers[groupId][msg.sender]; returnedOfferAmount = returnedOfferAmount.add(offeredValue); offers[groupId][msg.sender] = 0; } // Return the user's escrowed offer Ether. (bool success, ) = payable(msg.sender).call{ value: returnedOfferAmount }(""); require(success, "Returning canceled offer amount failed."); } /** Allows the Shop owner to accept any valid offer from a user. Once the Shop owner accepts the offer, the Ether is distributed according to fees and the item is minted to the user. @param _groupIds The item group IDs to process offers for. @param _bidders The specific bidder for each item group ID to accept. @param _itemIds The specific item ID within the group to mint for the bidder. @param _amounts The amount of specific item to mint for the bidder. */ function acceptOffers(uint256[] calldata _groupIds, address[] calldata _bidders, uint256[] calldata _itemIds, uint256[] calldata _amounts) public nonReentrant onlyOwner { require(_groupIds.length > 0, "You must accept an offer for at least one item."); require(_groupIds.length == _bidders.length, "Group IDs length cannot be mismatched with bidders length."); require(_groupIds.length == _itemIds.length, "Group IDs length cannot be mismatched with item IDs length."); require(_groupIds.length == _amounts.length, "Group IDs length cannot be mismatched with item amounts length."); // Accept all offers and disperse fees accordingly. uint256 feePercent = feeOwner.fee(); uint256 itemRoyaltyPercent = item.feeOwner().fee(); for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; address bidder = _bidders[i]; uint256 itemId = _itemIds[i]; uint256 amount = _amounts[i]; // Verify that the offer being accepted is still valid. uint256 price = prices[groupId]; require(price > 0, "You cannot accept an offer for an item that is not listed."); uint256 offeredPrice = offers[groupId][bidder]; require(offeredPrice >= price, "You cannot accept an offer for less than the current asking price."); // Split fees for this purchase. uint256 feeValue = offeredPrice.mul(feePercent).div(100000); uint256 royaltyValue = offeredPrice.mul(itemRoyaltyPercent).div(100000); (bool success, ) = payable(feeOwner.owner()).call{ value: feeValue }(""); require(success, "Platform fee transfer failed."); (success, ) = payable(item.feeOwner().owner()).call{ value: royaltyValue }(""); require(success, "Creator royalty transfer failed."); (success, ) = payable(owner()).call{ value: offeredPrice.sub(feeValue).sub(royaltyValue) }(""); require(success, "Shop owner transfer failed."); // Mint the item. item.mint(bidder, itemId, amount, ""); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC1155Receiver.sol"; import "../../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155NFTLockable.sol"; import "./Staker.sol"; /** @title A Shop contract for selling NFTs via direct minting through particular pools with specific participation requirements. @author Tim Clancy This launchpad contract is specifically optimized for SuperFarm direct use. */ contract ShopPlatformLaunchpad1155 is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 2; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A user-specified Fee1155 contract to support selling items from. Fee1155NFTLockable public item; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// A user-specified Staker contract to spend user points on. Staker[] public stakers; /** A limit on the number of items that a particular address may purchase across any number of pools in the launchpad. */ uint256 public globalPurchaseLimit; /// A mapping of addresses to the number of items each has purchased globally. mapping (address => uint256) public globalPurchaseCounts; /// The address of the orignal owner of the item contract. address public originalOwner; /// Whether ownership is locked to disable clawback. bool public ownershipLocked; /// A mapping of item group IDs to their next available issue number minus one. mapping (uint256 => uint256) public nextItemIssues; /// The next available ID to be assumed by the next whitelist added. uint256 public nextWhitelistId; /** A mapping of whitelist IDs to specific Whitelist elements. Whitelists may be shared between pools via specifying their ID in a pool requirement. */ mapping (uint256 => Whitelist) public whitelists; /// The next available ID to be assumed by the next pool added. uint256 public nextPoolId; /// A mapping of pool IDs to pools. mapping (uint256 => Pool) public pools; /** This struct is a source of mapping-free input to the `addPool` function. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. */ struct PoolInput { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; PoolRequirement requirement; } /** This struct tracks information about a single item pool in the Shop. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param purchaseCounts A mapping of addresses to the number of items each has purchased from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. @param itemGroups An array of all item groups currently present in this pool. @param currentPoolVersion A version number hashed with item group IDs before being used as keys to other mappings. This supports efficient invalidation of stale mappings. @param itemCaps A mapping of item group IDs to the maximum number this pool is allowed to mint. @param itemMinted A mapping of item group IDs to the number this pool has currently minted. @param itemPricesLength A mapping of item group IDs to the number of price assets available to purchase with. @param itemPrices A mapping of item group IDs to a mapping of available PricePair assets available to purchase with. */ struct Pool { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; mapping (address => uint256) purchaseCounts; PoolRequirement requirement; uint256[] itemGroups; uint256 currentPoolVersion; mapping (bytes32 => uint256) itemCaps; mapping (bytes32 => uint256) itemMinted; mapping (bytes32 => uint256) itemPricesLength; mapping (bytes32 => mapping (uint256 => PricePair)) itemPrices; } /** This struct tracks information about a prerequisite for a user to participate in a pool. @param requiredType A sentinel value for the specific type of asset being required. 0 = a pool which requires no specific assets to participate. 1 = an ERC-20 token, see `requiredAsset`. 2 = an NFT item, see `requiredAsset`. @param requiredAsset Some more specific information about the asset to require. If the `requiredType` is 1, we use this address to find the ERC-20 token that we should be specifically requiring holdings of. If the `requiredType` is 2, we use this address to find the item contract that we should be specifically requiring holdings of. @param requiredAmount The amount of the specified `requiredAsset` required. @param whitelistId The ID of an address whitelist to restrict participants in this pool. To participate, a purchaser must have their address present in the corresponding whitelist. Other requirements from `requiredType` apply. An ID of 0 is a sentinel value for no whitelist: a public pool. */ struct PoolRequirement { uint256 requiredType; address requiredAsset; uint256 requiredAmount; uint256 whitelistId; } /** This struct tracks information about a single asset with associated price that an item is being sold in the shop for. @param assetType A sentinel value for the specific type of asset being used. 0 = non-transferrable points from a Staker; see `asset`. 1 = Ether. 2 = an ERC-20 token, see `asset`. @param asset Some more specific information about the asset to charge in. If the `assetType` is 0, we convert the given address to an integer index for finding a specific Staker from `stakers`. If the `assetType` is 1, we ignore this field. If the `assetType` is 2, we use this address to find the ERC-20 token that we should be specifically charging with. @param price The amount of the specified `assetType` and `asset` to charge. */ struct PricePair { uint256 assetType; address asset; uint256 price; } /** This struct is a source of mapping-free input to the `addWhitelist` function. @param expiryBlock A block number after which this whitelist is automatically considered inactive, no matter the value of `isActive`. @param isActive Whether or not this whitelist is actively restricting purchases in blocks before `expiryBlock`. @param addresses An array of addresses to whitelist for participation in a purchase. */ struct WhitelistInput { uint256 expiryBlock; bool isActive; address[] addresses; } /** This struct tracks information about a single whitelist known to this launchpad. Whitelists may be shared across potentially-multiple item pools. @param expiryBlock A block number after which this whitelist is automatically considered inactive, no matter the value of `isActive`. @param isActive Whether or not this whitelist is actively restricting purchases in blocks before `expiryBlock`. @param currentWhitelistVersion A version number hashed with item group IDs before being used as keys to other mappings. This supports efficient invalidation of stale mappings. @param addresses A mapping of hashed addresses to a flag indicating whether this whitelist allows the address to participate in a purchase. */ struct Whitelist { uint256 expiryBlock; bool isActive; uint256 currentWhitelistVersion; mapping (bytes32 => bool) addresses; } /** This struct tracks information about a single item being sold in a pool. @param groupId The group ID of the specific NFT in the collection being sold by a pool. @param cap The maximum number of items that a pool may mint of the specified `groupId`. @param minted The number of items that a pool has currently minted of the specified `groupId`. @param prices The PricePair options that may be used to purchase this item from its pool. */ struct PoolItem { uint256 groupId; uint256 cap; uint256 minted; PricePair[] prices; } /** This struct contains the information gleaned from the `getPool` and `getPools` functions; it represents a single pool's data. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. @param itemMetadataUri The metadata URI of the item collection being sold by this launchpad. @param items An array of PoolItems representing each item for sale in the pool. */ struct PoolOutput { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; PoolRequirement requirement; string itemMetadataUri; PoolItem[] items; } /** This struct contains the information gleaned from the `getPool` and `getPools` functions; it represents a single pool's data. It also includes additional information relevant to a user's address lookup. @param name A name for the pool. @param startBlock The first block where this pool begins allowing purchases. @param endBlock The final block where this pool allows purchases. @param purchaseLimit The maximum number of items a single address may purchase from this pool. @param requirement A PoolRequirement requisite for users who want to participate in this pool. @param itemMetadataUri The metadata URI of the item collection being sold by this launchpad. @param items An array of PoolItems representing each item for sale in the pool. @param purchaseCount The amount of items purchased from this pool by the specified address. @param whitelistStatus Whether or not the specified address is whitelisted for this pool. */ struct PoolAddressOutput { string name; uint256 startBlock; uint256 endBlock; uint256 purchaseLimit; PoolRequirement requirement; string itemMetadataUri; PoolItem[] items; uint256 purchaseCount; bool whitelistStatus; } /// An event to track the original item contract owner clawing back ownership. event OwnershipClawback(); /// An event to track the original item contract owner locking future clawbacks. event OwnershipLocked(); /// An event to track the complete replacement of a pool's data. event PoolUpdated(uint256 poolId, PoolInput pool, uint256[] groupIds, uint256[] amounts, PricePair[][] pricePairs); /// An event to track the complete replacement of addresses in a whitelist. event WhitelistUpdated(uint256 whitelistId, address[] addresses); /// An event to track the addition of addresses to a whitelist. event WhitelistAddition(uint256 whitelistId, address[] addresses); /// An event to track the removal of addresses from a whitelist. event WhitelistRemoval(uint256 whitelistId, address[] addresses); // An event to track activating or deactivating a whitelist. event WhitelistActiveUpdate(uint256 whitelistId, bool isActive); // An event to track the purchase of items from a pool. event ItemPurchased(uint256 poolId, uint256[] itemIds, uint256 assetId, uint256[] amounts, address user); /// @dev a modifier which allows only `originalOwner` to call a function. modifier onlyOriginalOwner() { require(originalOwner == _msgSender(), "You are not the original owner of this contract."); _; } /** Construct a new Shop by providing it a FeeOwner. @param _item The address of the Fee1155NFTLockable item that will be minting sales. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. @param _stakers The addresses of any Stakers to permit spending points from. @param _globalPurchaseLimit A global limit on the number of items that a single address may purchase across all pools in the launchpad. */ constructor(Fee1155NFTLockable _item, FeeOwner _feeOwner, Staker[] memory _stakers, uint256 _globalPurchaseLimit) public { item = _item; feeOwner = _feeOwner; stakers = _stakers; globalPurchaseLimit = _globalPurchaseLimit; nextWhitelistId = 1; originalOwner = item.owner(); ownershipLocked = false; } /** A function which allows the caller to retrieve information about specific pools, the items for sale within, and the collection this launchpad uses. @param poolIds An array of pool IDs to retrieve information about. */ function getPools(uint256[] calldata poolIds) external view returns (PoolOutput[] memory) { PoolOutput[] memory poolOutputs = new PoolOutput[](poolIds.length); for (uint256 i = 0; i < poolIds.length; i++) { uint256 poolId = poolIds[i]; // Process output for each pool. PoolItem[] memory poolItems = new PoolItem[](pools[poolId].itemGroups.length); for (uint256 j = 0; j < pools[poolId].itemGroups.length; j++) { uint256 itemGroupId = pools[poolId].itemGroups[j]; bytes32 itemKey = keccak256(abi.encodePacked(pools[poolId].currentPoolVersion, itemGroupId)); // Parse each price the item is sold at. PricePair[] memory itemPrices = new PricePair[](pools[poolId].itemPricesLength[itemKey]); for (uint256 k = 0; k < pools[poolId].itemPricesLength[itemKey]; k++) { itemPrices[k] = pools[poolId].itemPrices[itemKey][k]; } // Track the item. poolItems[j] = PoolItem({ groupId: itemGroupId, cap: pools[poolId].itemCaps[itemKey], minted: pools[poolId].itemMinted[itemKey], prices: itemPrices }); } // Track the pool. poolOutputs[i] = PoolOutput({ name: pools[poolId].name, startBlock: pools[poolId].startBlock, endBlock: pools[poolId].endBlock, purchaseLimit: pools[poolId].purchaseLimit, requirement: pools[poolId].requirement, itemMetadataUri: item.metadataUri(), items: poolItems }); } // Return the pools. return poolOutputs; } /** A function which allows the caller to retrieve the number of items specific addresses have purchased from specific pools. @param poolIds The IDs of the pools to check for addresses in `purchasers`. @param purchasers The addresses to check the purchase counts for. */ function getPurchaseCounts(uint256[] calldata poolIds, address[] calldata purchasers) external view returns (uint256[][] memory) { uint256[][] memory purchaseCounts; for (uint256 i = 0; i < poolIds.length; i++) { uint256 poolId = poolIds[i]; for (uint256 j = 0; j < purchasers.length; j++) { address purchaser = purchasers[j]; purchaseCounts[j][i] = pools[poolId].purchaseCounts[purchaser]; } } return purchaseCounts; } /** A function which allows the caller to retrieve information about specific pools, the items for sale within, and the collection this launchpad uses. A provided address differentiates this function from `getPools`; the added address enables this function to retrieve pool data as well as whitelisting and purchase count details for the provided address. @param poolIds An array of pool IDs to retrieve information about. @param userAddress An address which enables this function to support additional relevant data lookups. */ function getPoolsWithAddress(uint256[] calldata poolIds, address userAddress) external view returns (PoolAddressOutput[] memory) { PoolAddressOutput[] memory poolOutputs = new PoolAddressOutput[](poolIds.length); for (uint256 i = 0; i < poolIds.length; i++) { uint256 poolId = poolIds[i]; // Process output for each pool. PoolItem[] memory poolItems = new PoolItem[](pools[poolId].itemGroups.length); for (uint256 j = 0; j < pools[poolId].itemGroups.length; j++) { uint256 itemGroupId = pools[poolId].itemGroups[j]; bytes32 itemKey = keccak256(abi.encodePacked(pools[poolId].currentPoolVersion, itemGroupId)); // Parse each price the item is sold at. PricePair[] memory itemPrices = new PricePair[](pools[poolId].itemPricesLength[itemKey]); for (uint256 k = 0; k < pools[poolId].itemPricesLength[itemKey]; k++) { itemPrices[k] = pools[poolId].itemPrices[itemKey][k]; } // Track the item. poolItems[j] = PoolItem({ groupId: itemGroupId, cap: pools[poolId].itemCaps[itemKey], minted: pools[poolId].itemMinted[itemKey], prices: itemPrices }); } // Track the pool. uint256 whitelistId = pools[poolId].requirement.whitelistId; bytes32 addressKey = keccak256(abi.encode(whitelists[whitelistId].currentWhitelistVersion, userAddress)); poolOutputs[i] = PoolAddressOutput({ name: pools[poolId].name, startBlock: pools[poolId].startBlock, endBlock: pools[poolId].endBlock, purchaseLimit: pools[poolId].purchaseLimit, requirement: pools[poolId].requirement, itemMetadataUri: item.metadataUri(), items: poolItems, purchaseCount: pools[poolId].purchaseCounts[userAddress], whitelistStatus: whitelists[whitelistId].addresses[addressKey] }); } // Return the pools. return poolOutputs; } /** A function which allows the original owner of the item contract to revoke ownership from the launchpad. */ function ownershipClawback() external onlyOriginalOwner { require(!ownershipLocked, "Ownership transfers have been locked."); item.transferOwnership(originalOwner); // Emit an event that the original owner of the item contract has clawed the contract back. emit OwnershipClawback(); } /** A function which allows the original owner of this contract to lock all future ownership clawbacks. */ function lockOwnership() external onlyOriginalOwner { ownershipLocked = true; // Emit an event that the contract's ownership transferrance is locked. emit OwnershipLocked(); } /** Allow the owner of the Shop to add a new pool of items to purchase. @param pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific Fee1155 item group IDs to sell in this pool, keyed to `_amounts`. @param _amounts The maximum amount of each particular groupId that can be sold by this pool. @param _pricePairs The asset address to price pairings to use for selling each item. */ function addPool(PoolInput calldata pool, uint256[] calldata _groupIds, uint256[] calldata _amounts, PricePair[][] memory _pricePairs) external onlyOwner { updatePool(nextPoolId, pool, _groupIds, _amounts, _pricePairs); // Increment the ID which will be used by the next pool added. nextPoolId = nextPoolId.add(1); } /** Allow the owner of the Shop to update an existing pool of items. @param poolId The ID of the pool to update. @param pool The PoolInput full of data defining the pool's operation. @param _groupIds The specific Fee1155 item group IDs to sell in this pool, keyed to `_amounts`. @param _amounts The maximum amount of each particular groupId that can be sold by this pool. @param _pricePairs The asset address to price pairings to use for selling each item. */ function updatePool(uint256 poolId, PoolInput calldata pool, uint256[] calldata _groupIds, uint256[] calldata _amounts, PricePair[][] memory _pricePairs) public onlyOwner { require(poolId <= nextPoolId, "You cannot update a non-existent pool."); require(pool.endBlock >= pool.startBlock, "You cannot create a pool which ends before it starts."); require(_groupIds.length > 0, "You must list at least one item group."); require(_groupIds.length == _amounts.length, "Item groups length cannot be mismatched with mintable amounts length."); require(_groupIds.length == _pricePairs.length, "Item groups length cannot be mismatched with price pair inputlength."); // Immediately store some given information about this pool. uint256 newPoolVersion = pools[poolId].currentPoolVersion.add(1); pools[poolId] = Pool({ name: pool.name, startBlock: pool.startBlock, endBlock: pool.endBlock, purchaseLimit: pool.purchaseLimit, itemGroups: _groupIds, currentPoolVersion: newPoolVersion, requirement: pool.requirement }); // Store the amount of each item group that this pool may mint. for (uint256 i = 0; i < _groupIds.length; i++) { require(_amounts[i] > 0, "You cannot add an item with no mintable amount."); bytes32 itemKey = keccak256(abi.encode(newPoolVersion, _groupIds[i])); pools[poolId].itemCaps[itemKey] = _amounts[i]; // Store future purchase information for the item group. for (uint256 j = 0; j < _pricePairs[i].length; j++) { pools[poolId].itemPrices[itemKey][j] = _pricePairs[i][j]; } pools[poolId].itemPricesLength[itemKey] = _pricePairs[i].length; } // Emit an event indicating that a pool has been updated. emit PoolUpdated(poolId, pool, _groupIds, _amounts, _pricePairs); } /** Allow the owner to add a new whitelist. @param whitelist The WhitelistInput full of data defining the new whitelist. */ function addWhitelist(WhitelistInput memory whitelist) external onlyOwner { updateWhitelist(nextWhitelistId, whitelist); // Increment the ID which will be used by the next whitelist added. nextWhitelistId = nextWhitelistId.add(1); } /** Allow the owner to update a whitelist. @param whitelistId The whitelist ID to replace with the new whitelist. @param whitelist The WhitelistInput full of data defining the new whitelist. */ function updateWhitelist(uint256 whitelistId, WhitelistInput memory whitelist) public onlyOwner { uint256 newWhitelistVersion = whitelists[whitelistId].currentWhitelistVersion.add(1); // Immediately store some given information about this whitelist. whitelists[whitelistId] = Whitelist({ expiryBlock: whitelist.expiryBlock, isActive: whitelist.isActive, currentWhitelistVersion: newWhitelistVersion }); // Invalidate the old mapping and store the new participation flags. for (uint256 i = 0; i < whitelist.addresses.length; i++) { bytes32 addressKey = keccak256(abi.encode(newWhitelistVersion, whitelist.addresses[i])); whitelists[whitelistId].addresses[addressKey] = true; } // Emit an event to track the new, replaced state of the whitelist. emit WhitelistUpdated(whitelistId, whitelist.addresses); } /** Allow the owner to add specified addresses to a whitelist. @param whitelistId The ID of the whitelist to add users to. @param addresses The array of addresses to add. */ function addToWhitelist(uint256 whitelistId, address[] calldata addresses) public onlyOwner { uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; for (uint256 i = 0; i < addresses.length; i++) { bytes32 addressKey = keccak256(abi.encode(whitelistVersion, addresses[i])); whitelists[whitelistId].addresses[addressKey] = true; } // Emit an event to track the addition of new addresses to the whitelist. emit WhitelistAddition(whitelistId, addresses); } /** Allow the owner to remove specified addresses from a whitelist. @param whitelistId The ID of the whitelist to remove users from. @param addresses The array of addresses to remove. */ function removeFromWhitelist(uint256 whitelistId, address[] calldata addresses) public onlyOwner { uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; for (uint256 i = 0; i < addresses.length; i++) { bytes32 addressKey = keccak256(abi.encode(whitelistVersion, addresses[i])); whitelists[whitelistId].addresses[addressKey] = false; } // Emit an event to track the removal of addresses from the whitelist. emit WhitelistRemoval(whitelistId, addresses); } /** Allow the owner to manually set the active status of a specific whitelist. @param whitelistId The ID of the whitelist to update the active flag for. @param isActive The boolean flag to enable or disable the whitelist. */ function setWhitelistActive(uint256 whitelistId, bool isActive) public onlyOwner { whitelists[whitelistId].isActive = isActive; // Emit an event to track whitelist activation status changes. emit WhitelistActiveUpdate(whitelistId, isActive); } /** A function which allows the caller to retrieve whether or not addresses can participate in some given whitelists. @param whitelistIds The IDs of the whitelists to check for addresses. @param addresses The addresses to check whitelist eligibility for. */ function getWhitelistStatus(uint256[] calldata whitelistIds, address[] calldata addresses) external view returns (bool[][] memory) { bool[][] memory whitelistStatus; for (uint256 i = 0; i < whitelistIds.length; i++) { uint256 whitelistId = whitelistIds[i]; uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; for (uint256 j = 0; j < addresses.length; j++) { bytes32 addressKey = keccak256(abi.encode(whitelistVersion, addresses[j])); whitelistStatus[j][i] = whitelists[whitelistId].addresses[addressKey]; } } return whitelistStatus; } /** Allow a user to purchase an item from a pool. @param poolId The ID of the particular pool that the user would like to purchase from. @param groupId The item group ID that the user would like to purchase. @param assetId The type of payment asset that the user would like to purchase with. @param amount The amount of item that the user would like to purchase. */ function mintFromPool(uint256 poolId, uint256 groupId, uint256 assetId, uint256 amount) external nonReentrant payable { require(amount > 0, "You must purchase at least one item."); require(poolId < nextPoolId, "You can only purchase items from an active pool."); // Verify that the asset being used in the purchase is valid. bytes32 itemKey = keccak256(abi.encode(pools[poolId].currentPoolVersion, groupId)); require(assetId < pools[poolId].itemPricesLength[itemKey], "Your specified asset ID is not valid."); // Verify that the pool is still running its sale. require(block.number >= pools[poolId].startBlock && block.number <= pools[poolId].endBlock, "This pool is not currently running its sale."); // Verify that the pool is respecting per-address global purchase limits. uint256 userGlobalPurchaseAmount = amount.add(globalPurchaseCounts[msg.sender]); require(userGlobalPurchaseAmount <= globalPurchaseLimit, "You may not purchase any more items from this sale."); // Verify that the pool is respecting per-address pool purchase limits. uint256 userPoolPurchaseAmount = amount.add(pools[poolId].purchaseCounts[msg.sender]); require(userPoolPurchaseAmount <= pools[poolId].purchaseLimit, "You may not purchase any more items from this pool."); // Verify that the pool is either public, whitelist-expired, or an address is whitelisted. { uint256 whitelistId = pools[poolId].requirement.whitelistId; uint256 whitelistVersion = whitelists[whitelistId].currentWhitelistVersion; bytes32 addressKey = keccak256(abi.encode(whitelistVersion, msg.sender)); bool addressWhitelisted = whitelists[whitelistId].addresses[addressKey]; require(whitelistId == 0 || block.number > whitelists[whitelistId].expiryBlock || addressWhitelisted || !whitelists[whitelistId].isActive, "You are not whitelisted on this pool."); } // Verify that the pool is not depleted by the user's purchase. uint256 newCirculatingTotal = pools[poolId].itemMinted[itemKey].add(amount); require(newCirculatingTotal <= pools[poolId].itemCaps[itemKey], "There are not enough items available for you to purchase."); // Verify that the user meets any requirements gating participation in this pool. PoolRequirement memory poolRequirement = pools[poolId].requirement; if (poolRequirement.requiredType == 1) { IERC20 requiredToken = IERC20(poolRequirement.requiredAsset); require(requiredToken.balanceOf(msg.sender) >= poolRequirement.requiredAmount, "You do not have enough required token to participate in this pool."); } // TODO: supporting item gate requirement requires upgrading the Fee1155 contract. // else if (poolRequirement.requiredType == 2) { // Fee1155 requiredItem = Fee1155(poolRequirement.requiredAsset); // require(requiredItem.balanceOf(msg.sender) >= poolRequirement.requiredAmount, // "You do not have enough required item to participate in this pool."); // } // Process payment for the user. // If the sentinel value for the point asset type is found, sell for points. // This involves converting the asset from an address to a Staker index. PricePair memory sellingPair = pools[poolId].itemPrices[itemKey][assetId]; if (sellingPair.assetType == 0) { uint256 stakerIndex = uint256(sellingPair.asset); stakers[stakerIndex].spendPoints(msg.sender, sellingPair.price.mul(amount)); // If the sentinel value for the Ether asset type is found, sell for Ether. } else if (sellingPair.assetType == 1) { uint256 etherPrice = sellingPair.price.mul(amount); require(msg.value >= etherPrice, "You did not send enough Ether to complete this purchase."); (bool success, ) = payable(owner()).call{ value: msg.value }(""); require(success, "Shop owner transfer failed."); // Otherwise, attempt to sell for an ERC20 token. } else { IERC20 sellingAsset = IERC20(sellingPair.asset); uint256 tokenPrice = sellingPair.price.mul(amount); require(sellingAsset.balanceOf(msg.sender) >= tokenPrice, "You do not have enough token to complete this purchase."); sellingAsset.safeTransferFrom(msg.sender, owner(), tokenPrice); } // If payment is successful, mint each of the user's purchased items. uint256[] memory itemIds = new uint256[](amount); uint256[] memory amounts = new uint256[](amount); uint256 nextIssueNumber = nextItemIssues[groupId]; { uint256 shiftedGroupId = groupId << 128; for (uint256 i = 1; i <= amount; i++) { uint256 itemId = shiftedGroupId.add(nextIssueNumber).add(i); itemIds[i - 1] = itemId; amounts[i - 1] = 1; } } // Mint the items. item.createNFT(msg.sender, itemIds, amounts, ""); // Update the tracker for available item issue numbers. nextItemIssues[groupId] = nextIssueNumber.add(amount); // Update the count of circulating items from this pool. pools[poolId].itemMinted[itemKey] = newCirculatingTotal; // Update the pool's count of items that a user has purchased. pools[poolId].purchaseCounts[msg.sender] = userPoolPurchaseAmount; // Update the global count of items that a user has purchased. globalPurchaseCounts[msg.sender] = userGlobalPurchaseAmount; // Emit an event indicating a successful purchase. emit ItemPurchased(poolId, itemIds, assetId, amounts, msg.sender); } /** Sweep all of a particular ERC-20 token from the contract. @param _token The token to sweep the balance from. */ function sweep(IERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransferFrom(address(this), msg.sender, balance); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @title An ERC-1155 item creation contract which specifies an associated FeeOwner who receives royalties from sales of created items. @author Tim Clancy The fee set by the FeeOwner on this Item is honored by Shop contracts. In addition to the inherited OpenZeppelin dependency, this uses ideas from the original ERC-1155 reference implementation. */ contract Fee1155NFTLockable is ERC1155, Ownable { using SafeMath for uint256; /// A version number for this fee-bearing 1155 item contract's interface. uint256 public version = 1; /// The ERC-1155 URI for looking up item metadata using {id} substitution. string public metadataUri; /// A user-specified FeeOwner to receive a portion of item sale earnings. FeeOwner public feeOwner; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /// A counter to enforce unique IDs for each item group minted. uint256 public nextItemGroupId; /// This mapping tracks the number of unique items within each item group. mapping (uint256 => uint256) public itemGroupSizes; /// Whether or not the item collection has been locked to further minting. bool public locked; /// An event for tracking the creation of an item group. event ItemGroupCreated(uint256 itemGroupId, uint256 itemGroupSize, address indexed creator); /** Construct a new ERC-1155 item with an associated FeeOwner fee. @param _uri The metadata URI to perform token ID substitution in. @param _feeOwner The address of a FeeOwner who receives earnings from this item. */ constructor(string memory _uri, FeeOwner _feeOwner, address _proxyRegistryAddress) public ERC1155(_uri) { metadataUri = _uri; feeOwner = _feeOwner; proxyRegistryAddress = _proxyRegistryAddress; nextItemGroupId = 0; locked = false; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** Allow the item owner to update the metadata URI of this collection. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external onlyOwner { metadataUri = _uri; } /** Allow the item owner to forever lock this contract to further item minting. */ function lock() external onlyOwner { locked = true; } /** Create a new NFT item group of a specific size. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param recipient The address to receive all NFTs within the newly-created group. @param ids The item IDs for the new items to create. @param amounts The amount of each corresponding item ID to create. @param data Any associated data to use on items minted in this transaction. */ function createNFT(address recipient, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external onlyOwner returns (uint256) { require(!locked, "You cannot create more NFTs on a locked collection."); require(ids.length > 0, "You cannot create an empty item group."); require(ids.length == amounts.length, "IDs length cannot be mismatched with amounts length."); // Create an item group of requested size using the next available ID. uint256 shiftedGroupId = nextItemGroupId << 128; itemGroupSizes[shiftedGroupId] = ids.length; // Mint the entire batch of items. _mintBatch(recipient, ids, amounts, data); // Increment our next item group ID and return our created item group ID. nextItemGroupId = nextItemGroupId.add(1); emit ItemGroupCreated(shiftedGroupId, ids.length, msg.sender); return shiftedGroupId; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title An asset staking contract. @author Tim Clancy This staking contract disburses tokens from its internal reservoir according to a fixed emission schedule. Assets can be assigned varied staking weights. This code is inspired by and modified from Sushi's Master Chef contract. https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChef.sol */ contract Staker is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // A user-specified, descriptive name for this Staker. string public name; // The token to disburse. IERC20 public token; // The amount of the disbursed token deposited by users. This is used for the // special case where a staking pool has been created for the disbursed token. // This is required to prevent the Staker itself from reducing emissions. uint256 public totalTokenDeposited; // A flag signalling whether the contract owner can add or set developers. bool public canAlterDevelopers; // An array of developer addresses for finding shares in the share mapping. address[] public developerAddresses; // A mapping of developer addresses to their percent share of emissions. // Share percentages are represented as 1/1000th of a percent. That is, a 1% // share of emissions should map an address to 1000. mapping (address => uint256) public developerShares; // A flag signalling whether or not the contract owner can alter emissions. bool public canAlterTokenEmissionSchedule; bool public canAlterPointEmissionSchedule; // The token emission schedule of the Staker. This emission schedule maps a // block number to the amount of tokens or points that should be disbursed with every // block beginning at said block number. struct EmissionPoint { uint256 blockNumber; uint256 rate; } // An array of emission schedule key blocks for finding emission rate changes. uint256 public tokenEmissionBlockCount; mapping (uint256 => EmissionPoint) public tokenEmissionBlocks; uint256 public pointEmissionBlockCount; mapping (uint256 => EmissionPoint) public pointEmissionBlocks; // Store the very earliest possible emission block for quick reference. uint256 MAX_INT = 2**256 - 1; uint256 internal earliestTokenEmissionBlock; uint256 internal earliestPointEmissionBlock; // Information for each pool that can be staked in. // - token: the address of the ERC20 asset that is being staked in the pool. // - strength: the relative token emission strength of this pool. // - lastRewardBlock: the last block number where token distribution occurred. // - tokensPerShare: accumulated tokens per share times 1e12. // - pointsPerShare: accumulated points per share times 1e12. struct PoolInfo { IERC20 token; uint256 tokenStrength; uint256 tokensPerShare; uint256 pointStrength; uint256 pointsPerShare; uint256 lastRewardBlock; } IERC20[] public poolTokens; // Stored information for each available pool per its token address. mapping (IERC20 => PoolInfo) public poolInfo; // Information for each user per staking pool: // - amount: the amount of the pool asset being provided by the user. // - tokenPaid: the value of the user's total earning that has been paid out. // -- pending reward = (user.amount * pool.tokensPerShare) - user.rewardDebt. // - pointPaid: the value of the user's total point earnings that has been paid out. struct UserInfo { uint256 amount; uint256 tokenPaid; uint256 pointPaid; } // Stored information for each user staking in each pool. mapping (IERC20 => mapping (address => UserInfo)) public userInfo; // The total sum of the strength of all pools. uint256 public totalTokenStrength; uint256 public totalPointStrength; // The total amount of the disbursed token ever emitted by this Staker. uint256 public totalTokenDisbursed; // Users additionally accrue non-token points for participating via staking. mapping (address => uint256) public userPoints; mapping (address => uint256) public userSpentPoints; // A map of all external addresses that are permitted to spend user points. mapping (address => bool) public approvedPointSpenders; // Events for depositing assets into the Staker and later withdrawing them. event Deposit(address indexed user, IERC20 indexed token, uint256 amount); event Withdraw(address indexed user, IERC20 indexed token, uint256 amount); // An event for tracking when a user has spent points. event SpentPoints(address indexed source, address indexed user, uint256 amount); /** Construct a new Staker by providing it a name and the token to disburse. @param _name The name of the Staker contract. @param _token The token to reward stakers in this contract with. */ constructor(string memory _name, IERC20 _token) public { name = _name; token = _token; token.approve(address(this), MAX_INT); canAlterDevelopers = true; canAlterTokenEmissionSchedule = true; earliestTokenEmissionBlock = MAX_INT; canAlterPointEmissionSchedule = true; earliestPointEmissionBlock = MAX_INT; } /** Add a new developer to the Staker or overwrite an existing one. This operation requires that developer address addition is not locked. @param _developerAddress The additional developer's address. @param _share The share in 1/1000th of a percent of each token emission sent to this new developer. */ function addDeveloper(address _developerAddress, uint256 _share) external onlyOwner { require(canAlterDevelopers, "This Staker has locked the addition of developers; no more may be added."); developerAddresses.push(_developerAddress); developerShares[_developerAddress] = _share; } /** Permanently forfeits owner ability to alter the state of Staker developers. Once called, this function is intended to give peace of mind to the Staker's developers and community that the fee structure is now immutable. */ function lockDevelopers() external onlyOwner { canAlterDevelopers = false; } /** A developer may at any time update their address or voluntarily reduce their share of emissions by calling this function from their current address. Note that updating a developer's share to zero effectively removes them. @param _newDeveloperAddress An address to update this developer's address. @param _newShare The new share in 1/1000th of a percent of each token emission sent to this developer. */ function updateDeveloper(address _newDeveloperAddress, uint256 _newShare) external { uint256 developerShare = developerShares[msg.sender]; require(developerShare > 0, "You are not a developer of this Staker."); require(_newShare <= developerShare, "You cannot increase your developer share."); developerShares[msg.sender] = 0; developerAddresses.push(_newDeveloperAddress); developerShares[_newDeveloperAddress] = _newShare; } /** Set new emission details to the Staker or overwrite existing ones. This operation requires that emission schedule alteration is not locked. @param _tokenSchedule An array of EmissionPoints defining the token schedule. @param _pointSchedule An array of EmissionPoints defining the point schedule. */ function setEmissions(EmissionPoint[] memory _tokenSchedule, EmissionPoint[] memory _pointSchedule) external onlyOwner { if (_tokenSchedule.length > 0) { require(canAlterTokenEmissionSchedule, "This Staker has locked the alteration of token emissions."); tokenEmissionBlockCount = _tokenSchedule.length; for (uint256 i = 0; i < tokenEmissionBlockCount; i++) { tokenEmissionBlocks[i] = _tokenSchedule[i]; if (earliestTokenEmissionBlock > _tokenSchedule[i].blockNumber) { earliestTokenEmissionBlock = _tokenSchedule[i].blockNumber; } } } require(tokenEmissionBlockCount > 0, "You must set the token emission schedule."); if (_pointSchedule.length > 0) { require(canAlterPointEmissionSchedule, "This Staker has locked the alteration of point emissions."); pointEmissionBlockCount = _pointSchedule.length; for (uint256 i = 0; i < pointEmissionBlockCount; i++) { pointEmissionBlocks[i] = _pointSchedule[i]; if (earliestPointEmissionBlock > _pointSchedule[i].blockNumber) { earliestPointEmissionBlock = _pointSchedule[i].blockNumber; } } } require(tokenEmissionBlockCount > 0, "You must set the point emission schedule."); } /** Permanently forfeits owner ability to alter the emission schedule. Once called, this function is intended to give peace of mind to the Staker's developers and community that the inflation rate is now immutable. */ function lockTokenEmissions() external onlyOwner { canAlterTokenEmissionSchedule = false; } /** Permanently forfeits owner ability to alter the emission schedule. Once called, this function is intended to give peace of mind to the Staker's developers and community that the inflation rate is now immutable. */ function lockPointEmissions() external onlyOwner { canAlterPointEmissionSchedule = false; } /** Returns the length of the developer address array. @return the length of the developer address array. */ function getDeveloperCount() external view returns (uint256) { return developerAddresses.length; } /** Returns the length of the staking pool array. @return the length of the staking pool array. */ function getPoolCount() external view returns (uint256) { return poolTokens.length; } /** Returns the amount of token that has not been disbursed by the Staker yet. @return the amount of token that has not been disbursed by the Staker yet. */ function getRemainingToken() external view returns (uint256) { return token.balanceOf(address(this)); } /** Allows the contract owner to add a new asset pool to the Staker or overwrite an existing one. @param _token The address of the asset to base this staking pool off of. @param _tokenStrength The relative strength of the new asset for earning token. @param _pointStrength The relative strength of the new asset for earning points. */ function addPool(IERC20 _token, uint256 _tokenStrength, uint256 _pointStrength) external onlyOwner { require(tokenEmissionBlockCount > 0 && pointEmissionBlockCount > 0, "Staking pools cannot be addded until an emission schedule has been defined."); uint256 lastTokenRewardBlock = block.number > earliestTokenEmissionBlock ? block.number : earliestTokenEmissionBlock; uint256 lastPointRewardBlock = block.number > earliestPointEmissionBlock ? block.number : earliestPointEmissionBlock; uint256 lastRewardBlock = lastTokenRewardBlock > lastPointRewardBlock ? lastTokenRewardBlock : lastPointRewardBlock; if (address(poolInfo[_token].token) == address(0)) { poolTokens.push(_token); totalTokenStrength = totalTokenStrength.add(_tokenStrength); totalPointStrength = totalPointStrength.add(_pointStrength); poolInfo[_token] = PoolInfo({ token: _token, tokenStrength: _tokenStrength, tokensPerShare: 0, pointStrength: _pointStrength, pointsPerShare: 0, lastRewardBlock: lastRewardBlock }); } else { totalTokenStrength = totalTokenStrength.sub(poolInfo[_token].tokenStrength).add(_tokenStrength); poolInfo[_token].tokenStrength = _tokenStrength; totalPointStrength = totalPointStrength.sub(poolInfo[_token].pointStrength).add(_pointStrength); poolInfo[_token].pointStrength = _pointStrength; } } /** Uses the emission schedule to calculate the total amount of staking reward token that was emitted between two specified block numbers. @param _fromBlock The block to begin calculating emissions from. @param _toBlock The block to calculate total emissions up to. */ function getTotalEmittedTokens(uint256 _fromBlock, uint256 _toBlock) public view returns (uint256) { require(_toBlock >= _fromBlock, "Tokens cannot be emitted from a higher block to a lower block."); uint256 totalEmittedTokens = 0; uint256 workingRate = 0; uint256 workingBlock = _fromBlock; for (uint256 i = 0; i < tokenEmissionBlockCount; ++i) { uint256 emissionBlock = tokenEmissionBlocks[i].blockNumber; uint256 emissionRate = tokenEmissionBlocks[i].rate; if (_toBlock < emissionBlock) { totalEmittedTokens = totalEmittedTokens.add(_toBlock.sub(workingBlock).mul(workingRate)); return totalEmittedTokens; } else if (workingBlock < emissionBlock) { totalEmittedTokens = totalEmittedTokens.add(emissionBlock.sub(workingBlock).mul(workingRate)); workingBlock = emissionBlock; } workingRate = emissionRate; } if (workingBlock < _toBlock) { totalEmittedTokens = totalEmittedTokens.add(_toBlock.sub(workingBlock).mul(workingRate)); } return totalEmittedTokens; } /** Uses the emission schedule to calculate the total amount of points emitted between two specified block numbers. @param _fromBlock The block to begin calculating emissions from. @param _toBlock The block to calculate total emissions up to. */ function getTotalEmittedPoints(uint256 _fromBlock, uint256 _toBlock) public view returns (uint256) { require(_toBlock >= _fromBlock, "Points cannot be emitted from a higher block to a lower block."); uint256 totalEmittedPoints = 0; uint256 workingRate = 0; uint256 workingBlock = _fromBlock; for (uint256 i = 0; i < pointEmissionBlockCount; ++i) { uint256 emissionBlock = pointEmissionBlocks[i].blockNumber; uint256 emissionRate = pointEmissionBlocks[i].rate; if (_toBlock < emissionBlock) { totalEmittedPoints = totalEmittedPoints.add(_toBlock.sub(workingBlock).mul(workingRate)); return totalEmittedPoints; } else if (workingBlock < emissionBlock) { totalEmittedPoints = totalEmittedPoints.add(emissionBlock.sub(workingBlock).mul(workingRate)); workingBlock = emissionBlock; } workingRate = emissionRate; } if (workingBlock < _toBlock) { totalEmittedPoints = totalEmittedPoints.add(_toBlock.sub(workingBlock).mul(workingRate)); } return totalEmittedPoints; } /** Update the pool corresponding to the specified token address. @param _token The address of the asset to update the corresponding pool for. */ function updatePool(IERC20 _token) internal { PoolInfo storage pool = poolInfo[_token]; if (block.number <= pool.lastRewardBlock) { return; } uint256 poolTokenSupply = pool.token.balanceOf(address(this)); if (address(_token) == address(token)) { poolTokenSupply = totalTokenDeposited; } if (poolTokenSupply <= 0) { pool.lastRewardBlock = block.number; return; } // Calculate tokens and point rewards for this pool. uint256 totalEmittedTokens = getTotalEmittedTokens(pool.lastRewardBlock, block.number); uint256 tokensReward = totalEmittedTokens.mul(pool.tokenStrength).div(totalTokenStrength).mul(1e12); uint256 totalEmittedPoints = getTotalEmittedPoints(pool.lastRewardBlock, block.number); uint256 pointsReward = totalEmittedPoints.mul(pool.pointStrength).div(totalPointStrength).mul(1e30); // Directly pay developers their corresponding share of tokens and points. for (uint256 i = 0; i < developerAddresses.length; ++i) { address developer = developerAddresses[i]; uint256 share = developerShares[developer]; uint256 devTokens = tokensReward.mul(share).div(100000); tokensReward = tokensReward - devTokens; uint256 devPoints = pointsReward.mul(share).div(100000); pointsReward = pointsReward - devPoints; token.safeTransferFrom(address(this), developer, devTokens.div(1e12)); userPoints[developer] = userPoints[developer].add(devPoints.div(1e30)); } // Update the pool rewards per share to pay users the amount remaining. pool.tokensPerShare = pool.tokensPerShare.add(tokensReward.div(poolTokenSupply)); pool.pointsPerShare = pool.pointsPerShare.add(pointsReward.div(poolTokenSupply)); pool.lastRewardBlock = block.number; } /** A function to easily see the amount of token rewards pending for a user on a given pool. Returns the pending reward token amount. @param _token The address of a particular staking pool asset to check for a pending reward. @param _user The user address to check for a pending reward. @return the pending reward token amount. */ function getPendingTokens(IERC20 _token, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_token]; UserInfo storage user = userInfo[_token][_user]; uint256 tokensPerShare = pool.tokensPerShare; uint256 poolTokenSupply = pool.token.balanceOf(address(this)); if (address(_token) == address(token)) { poolTokenSupply = totalTokenDeposited; } if (block.number > pool.lastRewardBlock && poolTokenSupply > 0) { uint256 totalEmittedTokens = getTotalEmittedTokens(pool.lastRewardBlock, block.number); uint256 tokensReward = totalEmittedTokens.mul(pool.tokenStrength).div(totalTokenStrength).mul(1e12); tokensPerShare = tokensPerShare.add(tokensReward.div(poolTokenSupply)); } return user.amount.mul(tokensPerShare).div(1e12).sub(user.tokenPaid); } /** A function to easily see the amount of point rewards pending for a user on a given pool. Returns the pending reward point amount. @param _token The address of a particular staking pool asset to check for a pending reward. @param _user The user address to check for a pending reward. @return the pending reward token amount. */ function getPendingPoints(IERC20 _token, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_token]; UserInfo storage user = userInfo[_token][_user]; uint256 pointsPerShare = pool.pointsPerShare; uint256 poolTokenSupply = pool.token.balanceOf(address(this)); if (address(_token) == address(token)) { poolTokenSupply = totalTokenDeposited; } if (block.number > pool.lastRewardBlock && poolTokenSupply > 0) { uint256 totalEmittedPoints = getTotalEmittedPoints(pool.lastRewardBlock, block.number); uint256 pointsReward = totalEmittedPoints.mul(pool.pointStrength).div(totalPointStrength).mul(1e30); pointsPerShare = pointsPerShare.add(pointsReward.div(poolTokenSupply)); } return user.amount.mul(pointsPerShare).div(1e30).sub(user.pointPaid); } /** Return the number of points that the user has available to spend. @return the number of points that the user has available to spend. */ function getAvailablePoints(address _user) public view returns (uint256) { uint256 concreteTotal = userPoints[_user]; uint256 pendingTotal = 0; for (uint256 i = 0; i < poolTokens.length; ++i) { IERC20 poolToken = poolTokens[i]; uint256 _pendingPoints = getPendingPoints(poolToken, _user); pendingTotal = pendingTotal.add(_pendingPoints); } uint256 spentTotal = userSpentPoints[_user]; return concreteTotal.add(pendingTotal).sub(spentTotal); } /** Return the total number of points that the user has ever accrued. @return the total number of points that the user has ever accrued. */ function getTotalPoints(address _user) external view returns (uint256) { uint256 concreteTotal = userPoints[_user]; uint256 pendingTotal = 0; for (uint256 i = 0; i < poolTokens.length; ++i) { IERC20 poolToken = poolTokens[i]; uint256 _pendingPoints = getPendingPoints(poolToken, _user); pendingTotal = pendingTotal.add(_pendingPoints); } return concreteTotal.add(pendingTotal); } /** Return the total number of points that the user has ever spent. @return the total number of points that the user has ever spent. */ function getSpentPoints(address _user) external view returns (uint256) { return userSpentPoints[_user]; } /** Deposit some particular assets to a particular pool on the Staker. @param _token The asset to stake into its corresponding pool. @param _amount The amount of the provided asset to stake. */ function deposit(IERC20 _token, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_token]; require(pool.tokenStrength > 0 || pool.pointStrength > 0, "You cannot deposit assets into an inactive pool."); UserInfo storage user = userInfo[_token][msg.sender]; updatePool(_token); if (user.amount > 0) { uint256 pendingTokens = user.amount.mul(pool.tokensPerShare).div(1e12).sub(user.tokenPaid); token.safeTransferFrom(address(this), msg.sender, pendingTokens); totalTokenDisbursed = totalTokenDisbursed.add(pendingTokens); uint256 pendingPoints = user.amount.mul(pool.pointsPerShare).div(1e30).sub(user.pointPaid); userPoints[msg.sender] = userPoints[msg.sender].add(pendingPoints); } pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); if (address(_token) == address(token)) { totalTokenDeposited = totalTokenDeposited.add(_amount); } user.amount = user.amount.add(_amount); user.tokenPaid = user.amount.mul(pool.tokensPerShare).div(1e12); user.pointPaid = user.amount.mul(pool.pointsPerShare).div(1e30); emit Deposit(msg.sender, _token, _amount); } /** Withdraw some particular assets from a particular pool on the Staker. @param _token The asset to withdraw from its corresponding staking pool. @param _amount The amount of the provided asset to withdraw. */ function withdraw(IERC20 _token, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_token]; UserInfo storage user = userInfo[_token][msg.sender]; require(user.amount >= _amount, "You cannot withdraw that much of the specified token; you are not owed it."); updatePool(_token); uint256 pendingTokens = user.amount.mul(pool.tokensPerShare).div(1e12).sub(user.tokenPaid); token.safeTransferFrom(address(this), msg.sender, pendingTokens); totalTokenDisbursed = totalTokenDisbursed.add(pendingTokens); uint256 pendingPoints = user.amount.mul(pool.pointsPerShare).div(1e30).sub(user.pointPaid); userPoints[msg.sender] = userPoints[msg.sender].add(pendingPoints); if (address(_token) == address(token)) { totalTokenDeposited = totalTokenDeposited.sub(_amount); } user.amount = user.amount.sub(_amount); user.tokenPaid = user.amount.mul(pool.tokensPerShare).div(1e12); user.pointPaid = user.amount.mul(pool.pointsPerShare).div(1e30); pool.token.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _token, _amount); } /** Allows the owner of this Staker to grant or remove approval to an external spender of the points that users accrue from staking resources. @param _spender The external address allowed to spend user points. @param _approval The updated user approval status. */ function approvePointSpender(address _spender, bool _approval) external onlyOwner { approvedPointSpenders[_spender] = _approval; } /** Allows an approved spender of points to spend points on behalf of a user. @param _user The user whose points are being spent. @param _amount The amount of the user's points being spent. */ function spendPoints(address _user, uint256 _amount) external { require(approvedPointSpenders[msg.sender], "You are not permitted to spend user points."); uint256 _userPoints = getAvailablePoints(_user); require(_userPoints >= _amount, "The user does not have enough points to spend the requested amount."); userSpentPoints[_user] = userSpentPoints[_user].add(_amount); emit SpentPoints(msg.sender, _user, _amount); } /** Sweep all of a particular ERC-20 token from the contract. @param _token The token to sweep the balance from. */ function sweep(IERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransferFrom(address(this), msg.sender, balance); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./Token.sol"; import "./Staker.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Stakers. @author Tim Clancy This is the governing registry of all SuperFarm Staker assets. */ contract FarmStakerRecords is Ownable, ReentrancyGuard { /// A struct used to specify token and pool strengths for adding a pool. struct PoolData { IERC20 poolToken; uint256 tokenStrength; uint256 pointStrength; } /// A version number for this record contract's interface. uint256 public version = 1; /// A mapping for an array of all Stakers deployed by a particular address. mapping (address => address[]) public farmRecords; /// An event for tracking the creation of a new Staker. event FarmCreated(address indexed farmAddress, address indexed creator); /** Create a Staker on behalf of the owner calling this function. The Staker supports immediate specification of the emission schedule and pool strength. @param _name The name of the Staker to create. @param _token The Token to reward stakers in the Staker with. @param _tokenSchedule An array of EmissionPoints defining the token schedule. @param _pointSchedule An array of EmissionPoints defining the point schedule. @param _initialPools An array of pools to initially add to the new Staker. */ function createFarm(string calldata _name, IERC20 _token, Staker.EmissionPoint[] memory _tokenSchedule, Staker.EmissionPoint[] memory _pointSchedule, PoolData[] calldata _initialPools) nonReentrant external returns (Staker) { Staker newStaker = new Staker(_name, _token); // Establish the emissions schedule and add the token pools. newStaker.setEmissions(_tokenSchedule, _pointSchedule); for (uint256 i = 0; i < _initialPools.length; i++) { newStaker.addPool(_initialPools[i].poolToken, _initialPools[i].tokenStrength, _initialPools[i].pointStrength); } // Transfer ownership of the new Staker to the user then store a reference. newStaker.transferOwnership(msg.sender); address stakerAddress = address(newStaker); farmRecords[msg.sender].push(stakerAddress); emit FarmCreated(stakerAddress, msg.sender); return newStaker; } /** Allow a user to add an existing Staker contract to the registry. @param _farmAddress The address of the Staker contract to add for this user. */ function addFarm(address _farmAddress) external { farmRecords[msg.sender].push(_farmAddress); } /** Get the number of entries in the Staker records mapping for the given user. @return The number of Stakers added for a given address. */ function getFarmCount(address _user) external view returns (uint256) { return farmRecords[_user].length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** @title A basic ERC-20 token with voting functionality. @author Tim Clancy This contract is used when deploying SuperFarm ERC-20 tokens. This token is created with a fixed, immutable cap and includes voting rights. Voting functionality is copied and modified from Sushi, and in turn from YAM: 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 in turn copied and modified from COMPOUND: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol */ contract Token is ERC20Capped, Ownable { /// A version number for this Token contract's interface. uint256 public version = 1; /** Construct a new Token by providing it a name, ticker, and supply cap. @param _name The name of the new Token. @param _ticker The ticker symbol of the new Token. @param _cap The supply cap of the new Token. */ constructor (string memory _name, string memory _ticker, uint256 _cap) public ERC20(_name, _ticker) ERC20Capped(_cap) { } /** * @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); } /** Allows Token creator to mint `_amount` of this Token to the address `_to`. New tokens of this Token cannot be minted if it would exceed the supply cap. Users are delegated votes when they are minted Token. @param _to the address to mint Tokens to. @param _amount the amount of new Token to mint. */ function mint(address _to, uint256 _amount) external onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** Allows users to transfer tokens to a recipient, moving delegated votes with the transfer. @param recipient The address to transfer tokens to. @param amount The amount of tokens to send to `recipient`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); _moveDelegates(_delegates[msg.sender], _delegates[recipient], amount); return true; } /// @dev A mapping to record delegates for each address. mapping (address => address) internal _delegates; /// A checkpoint structure to mark some number of votes from a given block. struct Checkpoint { uint32 fromBlock; uint256 votes; } /// A mapping to record indexed Checkpoint votes for each address. mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// A mapping to record the number of Checkpoints for each address. mapping (address => uint32) public numCheckpoints; /// The EIP-712 typehash for the contract's domain. bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// 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)"); /// A mapping to record per-address states for signing / validating signatures. mapping (address => uint) public nonces; /// An event emitted when an address changes its delegate. event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// An event emitted when the vote balance of a delegated address changes. event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** Return the address delegated to by `delegator`. @return The address delegated to by `delegator`. */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** 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); } /** Delegate votes from signatory to `delegatee`. @param delegatee The address to delegate votes to. @param nonce The contract state required for signature matching. @param expiry The time at which to expire the signature. @param v The recovery byte of the signature. @param r Half of the ECDSA signature pair. @param s Half of the ECDSA signature pair. */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Invalid signature."); require(nonce == nonces[signatory]++, "Invalid nonce."); require(now <= expiry, "Signature expired."); return _delegate(signatory, delegatee); } /** Get the current votes balance for the address `account`. @param account The address to get the votes balance of. @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; } /** Determine the prior number of votes for an address as of a block number. @dev The block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address to check. @param blockNumber The block number to get the vote balance at. @return The number of votes the account had as of the given block. */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "The specified block is not yet finalized."); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check the most recent balance. if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Then check the 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; } /** An internal function to actually perform the delegation of votes. @param delegator The address delegating to `delegatee`. @param delegatee The address receiving delegated votes. */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; /* console.log('a-', currentDelegate, delegator, delegatee); */ emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } /** An internal function to move delegated vote amounts between addresses. @param srcRep the previous representative who received delegated votes. @param dstRep the new representative to receive these delegated votes. @param amount the amount of delegated votes to move between representatives. */ function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { // Decrease the number of votes delegated to the previous representative. if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } // Increase the number of votes delegated to the new representative. if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** An internal function to write a checkpoint of modified vote amounts. This function is guaranteed to add at most one checkpoint per block. @param delegatee The address whose vote count is changed. @param nCheckpoints The number of checkpoints by address `delegatee`. @param oldVotes The prior vote count of address `delegatee`. @param newVotes The new vote count of address `delegatee`. */ function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = safe32(block.number, "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); } /** A function to safely limit a number to less than 2^32. @param n the number to limit. @param errorMessage the error message to revert with should `n` be too large. @return The number `n` limited to 32 bits. */ function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** A function to return the ID of the contract's particular network or chain. @return The ID of the contract's network or chain. */ function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { using SafeMath for uint256; uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap_) internal { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./Token.sol"; /** @title A vault for securely holding tokens. @author Tim Clancy The purpose of this contract is to hold a single type of ERC-20 token securely behind a Compound Timelock governed by a Gnosis MultiSigWallet. Tokens may only leave the vault with multisignature permission and after passing through a mandatory timelock. The justification for the timelock is such that, if the multisignature wallet is ever compromised, the team will have two days to act in mitigating the potential damage from the attacker's `sentTokens` call. Such mitigation efforts may include calling `panic` from a separate, uncompromised and non-timelocked multisignature wallet, or finding some way to issue a new token entirely. */ contract TokenVault is Ownable, ReentrancyGuard { using SafeMath for uint256; /// A version number for this TokenVault contract's interface. uint256 public version = 1; /// A user-specified, descriptive name for this TokenVault. string public name; /// The token to hold safe. Token public token; /** The panic owner is an optional address allowed to immediately send the contents of the vault to the address specified in `panicDestination`. The intention of this system is to support a series of cascading vaults secured by their own multisignature wallets. If, for instance, vault one is compromised via its attached multisignature wallet, vault two could intercede to save the tokens from vault one before the malicious token send clears the owning timelock. */ address public panicOwner; /// An optional address where tokens may be immediately sent by `panicOwner`. address public panicDestination; /** A counter to limit the number of times a vault can panic before burning the underlying supply of tokens. This limit is in place to protect against a situation where multiple vaults linked in a circle are all compromised. In the event of such an attack, this still gives the original multisignature holders the chance to burn the tokens by repeatedly calling `panic` before the attacker can use `sendTokens`. */ uint256 public panicLimit; /// A counter for the number of times this vault has panicked. uint256 public panicCounter; /// A flag to determine whether or not this vault can alter its `panicOwner` and `panicDestination`. bool public canAlterPanicDetails; /// An event for tracking a change in panic details. event PanicDetailsChange(address indexed panicOwner, address indexed panicDestination); /// An event for tracking a lock on alteration of panic details. event PanicDetailsLocked(); /// An event for tracking a disbursement of tokens. event TokenSend(uint256 tokenAmount); /// An event for tracking a panic transfer of tokens. event PanicTransfer(uint256 panicCounter, uint256 tokenAmount, address indexed destination); /// An event for tracking a panic burn of tokens. event PanicBurn(uint256 panicCounter, uint256 tokenAmount); /// @dev a modifier which allows only `panicOwner` to call a function. modifier onlyPanicOwner() { require(panicOwner == _msgSender(), "TokenVault: caller is not the panic owner"); _; } /** Construct a new TokenVault by providing it a name and the token to disburse. @param _name The name of the TokenVault. @param _token The token to store and disburse. @param _panicOwner The address to grant emergency withdrawal powers to. @param _panicDestination The destination to withdraw to in emergency. @param _panicLimit A limit for the number of times `panic` can be called before tokens burn. */ constructor(string memory _name, Token _token, address _panicOwner, address _panicDestination, uint256 _panicLimit) public { name = _name; token = _token; panicOwner = _panicOwner; panicDestination = _panicDestination; panicLimit = _panicLimit; panicCounter = 0; canAlterPanicDetails = true; uint256 MAX_INT = 2**256 - 1; token.approve(address(this), MAX_INT); } /** Allows the owner of the TokenVault to update the `panicOwner` and `panicDestination` details governing its panic functionality. @param _panicOwner The new panic owner to set. @param _panicDestination The new emergency destination to send tokens to. */ function changePanicDetails(address _panicOwner, address _panicDestination) external nonReentrant onlyOwner { require(canAlterPanicDetails, "You cannot change panic details on a vault which is locked."); panicOwner = _panicOwner; panicDestination = _panicDestination; emit PanicDetailsChange(panicOwner, panicDestination); } /** Allows the owner of the TokenVault to lock the vault to all future panic detail changes. */ function lock() external nonReentrant onlyOwner { canAlterPanicDetails = false; emit PanicDetailsLocked(); } /** Allows the TokenVault owner to send tokens out of the vault. @param _recipients The array of addresses to receive tokens. @param _amounts The array of amounts sent to each address in `_recipients`. */ function sendTokens(address[] calldata _recipients, uint256[] calldata _amounts) external nonReentrant onlyOwner { require(_recipients.length > 0, "You must send tokens to at least one recipient."); require(_recipients.length == _amounts.length, "Recipients length cannot be mismatched with amounts length."); // Iterate through every specified recipient and send tokens. uint256 totalAmount = 0; for (uint256 i = 0; i < _recipients.length; i++) { address recipient = _recipients[i]; uint256 amount = _amounts[i]; token.transfer(recipient, amount); totalAmount = totalAmount.add(amount); } emit TokenSend(totalAmount); } /** Allow the TokenVault's `panicOwner` to immediately send its contents to a predefined `panicDestination`. This can be used to circumvent the timelock in case of an emergency. */ function panic() external nonReentrant onlyPanicOwner { uint256 totalBalance = token.balanceOf(address(this)); // If the panic limit is reached, burn the tokens. if (panicCounter == panicLimit) { token.burn(totalBalance); emit PanicBurn(panicCounter, totalBalance); // Otherwise, drain the vault to the panic destination. } else { if (panicDestination == address(0)) { token.burn(totalBalance); emit PanicBurn(panicCounter, totalBalance); } else { token.transfer(panicDestination, totalBalance); emit PanicTransfer(panicCounter, totalBalance, panicDestination); } panicCounter = panicCounter.add(1); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title A token vesting contract for streaming claims. @author SuperFarm This vesting contract allows users to claim vested tokens with every block. */ contract VestStream is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint64; using SafeERC20 for IERC20; /// The token to disburse in vesting. IERC20 public token; // Information for a particular token claim. // - totalAmount: the total size of the token claim. // - startTime: the timestamp in seconds when the vest begins. // - endTime: the timestamp in seconds when the vest completely matures. // - lastCLaimTime: the timestamp in seconds of the last time the claim was utilized. // - amountClaimed: the total amount claimed from the entire claim. struct Claim { uint256 totalAmount; uint64 startTime; uint64 endTime; uint64 lastClaimTime; uint256 amountClaimed; } // A mapping of addresses to the claim received. mapping(address => Claim) private claims; /// An event for tracking the creation of a token vest claim. event ClaimCreated(address creator, address beneficiary); /// An event for tracking a user claiming some of their vested tokens. event Claimed(address beneficiary, uint256 amount); /** Construct a new VestStream by providing it a token to disburse. @param _token The token to vest to claimants in this contract. */ constructor(IERC20 _token) public { token = _token; uint256 MAX_INT = 2**256 - 1; token.approve(address(this), MAX_INT); } /** A function which allows the caller to retrieve information about a specific claim via its beneficiary. @param beneficiary the beneficiary to query claims for. */ function getClaim(address beneficiary) external view returns (Claim memory) { require(beneficiary != address(0), "The zero address may not be a claim beneficiary."); return claims[beneficiary]; } /** A function which allows the caller to retrieve information about a specific claim's remaining claimable amount. @param beneficiary the beneficiary to query claims for. */ function claimableAmount(address beneficiary) public view returns (uint256) { Claim memory claim = claims[beneficiary]; // Early-out if the claim has not started yet. if (claim.startTime == 0 || block.timestamp < claim.startTime) { return 0; } // Calculate the current releasable token amount. uint64 currentTimestamp = uint64(block.timestamp) > claim.endTime ? claim.endTime : uint64(block.timestamp); uint256 claimPercent = currentTimestamp.sub(claim.startTime).mul(1e18).div(claim.endTime.sub(claim.startTime)); uint256 claimAmount = claim.totalAmount.mul(claimPercent).div(1e18); // Reduce the unclaimed amount by the amount already claimed. uint256 unclaimedAmount = claimAmount.sub(claim.amountClaimed); return unclaimedAmount; } /** Sweep all of a particular ERC-20 token from the contract. @param _token The token to sweep the balance from. */ function sweep(IERC20 _token) external onlyOwner { uint256 balance = _token.balanceOf(address(this)); _token.safeTransferFrom(address(this), msg.sender, balance); } /** A function which allows the caller to create toke vesting claims for some beneficiaries. The disbursement token will be taken from the claim creator. @param _beneficiaries an array of addresses to construct token claims for. @param _totalAmounts the total amount of tokens to be disbursed to each beneficiary. @param _startTime a timestamp when this claim is to begin vesting. @param _endTime a timestamp when this claim is to reach full maturity. */ function createClaim(address[] memory _beneficiaries, uint256[] memory _totalAmounts, uint64 _startTime, uint64 _endTime) external onlyOwner { require(_beneficiaries.length > 0, "You must specify at least one beneficiary for a claim."); require(_beneficiaries.length == _totalAmounts.length, "Beneficiaries and their amounts may not be mismatched."); require(_endTime >= _startTime, "You may not create a claim which ends before it starts."); // After validating the details for this token claim, initialize a claim for // each specified beneficiary. for (uint i = 0; i < _beneficiaries.length; i++) { address _beneficiary = _beneficiaries[i]; uint256 _totalAmount = _totalAmounts[i]; require(_beneficiary != address(0), "The zero address may not be a beneficiary."); require(_totalAmount > 0, "You may not create a zero-token claim."); // Establish a claim for this particular beneficiary. Claim memory claim = Claim({ totalAmount: _totalAmount, startTime: _startTime, endTime: _endTime, lastClaimTime: _startTime, amountClaimed: 0 }); claims[_beneficiary] = claim; emit ClaimCreated(msg.sender, _beneficiary); } } /** A function which allows the caller to send a claim's unclaimed amount to the beneficiary of the claim. @param beneficiary the beneficiary to claim for. */ function claim(address beneficiary) external nonReentrant { Claim memory _claim = claims[beneficiary]; // Verify that the claim is still active. require(_claim.lastClaimTime < _claim.endTime, "This claim has already been completely claimed."); // Calculate the current releasable token amount. uint64 currentTimestamp = uint64(block.timestamp) > _claim.endTime ? _claim.endTime : uint64(block.timestamp); uint256 claimPercent = currentTimestamp.sub(_claim.startTime).mul(1e18).div(_claim.endTime.sub(_claim.startTime)); uint256 claimAmount = _claim.totalAmount.mul(claimPercent).div(1e18); // Reduce the unclaimed amount by the amount already claimed. uint256 unclaimedAmount = claimAmount.sub(_claim.amountClaimed); // Transfer the unclaimed tokens to the beneficiary. token.safeTransferFrom(address(this), beneficiary, unclaimedAmount); // Update the amount currently claimed by the user. _claim.amountClaimed = claimAmount; // Update the last time the claim was utilized. _claim.lastClaimTime = currentTimestamp; // Update the claim structure being tracked. claims[beneficiary] = _claim; // Emit an event for this token claim. emit Claimed(beneficiary, unclaimedAmount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** @title An OpenSea mock proxy contract which we use to test whitelisting. @author OpenSea */ contract MockProxyRegistry is Ownable { using SafeMath for uint256; /// A mapping of testing proxies. mapping(address => address) public proxies; /** Allow the registry owner to set a proxy on behalf of an address. @param _address The address that the proxy will act on behalf of. @param _proxyForAddress The proxy that will act on behalf of the address. */ function setProxy(address _address, address _proxyForAddress) external onlyOwner { proxies[_address] = _proxyForAddress; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; /** @title A simple Shop contract for selling ERC-1155s for Ether via direct minting. @author Tim Clancy This contract is a limited subset of the Shop1155 contract designed to mint items directly to the user upon purchase. */ contract ShopEtherMinter1155 is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 1; /// @dev A mask for isolating an item's group ID. uint256 constant GROUP_MASK = uint256(uint128(~0)) << 128; /// A user-specified Fee1155 contract to support selling items from. Fee1155 public item; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// The Shop's inventory of item groups for sale. uint256[] public inventory; /// The Shop's price for each item group. mapping (uint256 => uint256) public prices; /** Construct a new Shop by providing it a FeeOwner. @param _item The address of the Fee1155 item that will be minting sales. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. */ constructor(Fee1155 _item, FeeOwner _feeOwner) public { item = _item; feeOwner = _feeOwner; } /** Returns the length of the inventory array. @return the length of the inventory array. */ function getInventoryCount() external view returns (uint256) { return inventory.length; } /** Allows the Shop owner to list a new set of NFT items for sale. @param _groupIds The item group IDs to list for sale in this shop. @param _prices The corresponding purchase price to mint an item of each group. */ function listItems(uint256[] calldata _groupIds, uint256[] calldata _prices) external onlyOwner { require(_groupIds.length > 0, "You must list at least one item."); require(_groupIds.length == _prices.length, "Items length cannot be mismatched with prices length."); // Iterate through every specified item group to list items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; uint256 price = _prices[i]; inventory.push(groupId); prices[groupId] = price; } } /** Allows the Shop owner to remove items from sale. @param _groupIds The group IDs currently listed in the shop to take off sale. */ function removeItems(uint256[] calldata _groupIds) external onlyOwner { require(_groupIds.length > 0, "You must remove at least one item."); // Iterate through every specified item group to remove items. for (uint256 i = 0; i < _groupIds.length; i++) { uint256 groupId = _groupIds[i]; prices[groupId] = 0; } } /** Allows any user to purchase items from this Shop. Users supply specfic item IDs within the groups listed for sale and supply the corresponding amount of Ether to cover the purchase prices. @param _itemIds The specific item IDs to purchase from this shop. */ function purchaseItems(uint256[] calldata _itemIds) public nonReentrant payable { require(_itemIds.length > 0, "You must purchase at least one item."); // Iterate through every specified item to list items. uint256 feePercent = feeOwner.fee(); uint256 itemRoyaltyPercent = item.feeOwner().fee(); for (uint256 i = 0; i < _itemIds.length; i++) { uint256 itemId = _itemIds[i]; uint256 groupId = itemId & GROUP_MASK; uint256 price = prices[groupId]; require(price > 0, "You cannot purchase an item that is not listed."); // Split fees for this purchase. uint256 feeValue = price.mul(feePercent).div(100000); uint256 royaltyValue = price.mul(itemRoyaltyPercent).div(100000); (bool success, ) = payable(feeOwner.owner()).call{ value: feeValue }(""); require(success, "Platform fee transfer failed."); (success, ) = payable(item.feeOwner().owner()).call{ value: royaltyValue }(""); require(success, "Creator royalty transfer failed."); (success, ) = payable(owner()).call{ value: price.sub(feeValue).sub(royaltyValue) }(""); require(success, "Shop owner transfer failed."); // Mint the item. item.mint(msg.sender, itemId, 1, ""); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // TRUFFLE import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract SuperVestCliff { using SafeMath for uint256; using Address for address; address public tokenAddress; event Claimed( address owner, address beneficiary, uint256 amount, uint256 index ); event ClaimCreated(address owner, address beneficiary, uint256 index); struct Claim { address owner; address beneficiary; uint256[] timePeriods; uint256[] tokenAmounts; uint256 totalAmount; uint256 amountClaimed; uint256 periodsClaimed; } Claim[] private claims; mapping(address => uint256[]) private _ownerClaims; mapping(address => uint256[]) private _beneficiaryClaims; constructor(address _tokenAddress) public { tokenAddress = _tokenAddress; } /** * Get Owner Claims * * @param owner - Claim Owner Address */ function ownerClaims(address owner) external view returns (uint256[] memory) { require(owner != address(0), "Owner address cannot be 0"); return _ownerClaims[owner]; } /** * Get Beneficiary Claims * * @param beneficiary - Claim Owner Address */ function beneficiaryClaims(address beneficiary) external view returns (uint256[] memory) { require(beneficiary != address(0), "Beneficiary address cannot be 0"); return _beneficiaryClaims[beneficiary]; } /** * Get Amount Claimed * * @param index - Claim Index */ function claimed(uint256 index) external view returns (uint256) { return claims[index].amountClaimed; } /** * Get Total Claim Amount * * @param index - Claim Index */ function totalAmount(uint256 index) external view returns (uint256) { return claims[index].totalAmount; } /** * Get Time Periods of Claim * * @param index - Claim Index */ function timePeriods(uint256 index) external view returns (uint256[] memory) { return claims[index].timePeriods; } /** * Get Token Amounts of Claim * * @param index - Claim Index */ function tokenAmounts(uint256 index) external view returns (uint256[] memory) { return claims[index].tokenAmounts; } /** * Create a Claim - To Vest Tokens to Beneficiary * * @param _beneficiary - Tokens will be claimed by _beneficiary * @param _timePeriods - uint256 Array of Epochs * @param _tokenAmounts - uin256 Array of Amounts to transfer at each time period */ function createClaim( address _beneficiary, uint256[] memory _timePeriods, uint256[] memory _tokenAmounts ) public returns (bool) { require( _timePeriods.length == _tokenAmounts.length, "_timePeriods & _tokenAmounts length mismatch" ); require(tokenAddress.isContract(), "Invalid tokenAddress"); require(_beneficiary != address(0), "Cannot Vest to address 0"); // Calculate total amount uint256 _totalAmount = 0; for (uint256 i = 0; i < _tokenAmounts.length; i++) { _totalAmount = _totalAmount.add(_tokenAmounts[i]); } require(_totalAmount > 0, "Provide Token Amounts to Vest"); require( ERC20(tokenAddress).allowance(msg.sender, address(this)) >= _totalAmount, "Provide token allowance to SuperVestCliff contract" ); // Transfer Tokens to SuperStreamClaim ERC20(tokenAddress).transferFrom( msg.sender, address(this), _totalAmount ); // Create Claim Claim memory claim = Claim({ owner: msg.sender, beneficiary: _beneficiary, timePeriods: _timePeriods, tokenAmounts: _tokenAmounts, totalAmount: _totalAmount, amountClaimed: 0, periodsClaimed: 0 }); claims.push(claim); uint256 index = claims.length - 1; // Map Claim Index to Owner & Beneficiary _ownerClaims[msg.sender].push(index); _beneficiaryClaims[_beneficiary].push(index); emit ClaimCreated(msg.sender, _beneficiary, index); return true; } /** * Claim Tokens * * @param index - Index of the Claim */ function claim(uint256 index) external { Claim storage claim = claims[index]; // Check if msg.sender is the beneficiary require( claim.beneficiary == msg.sender, "Only beneficiary can claim tokens" ); // Check if anything is left to release require( claim.periodsClaimed < claim.timePeriods.length, "Nothing to release" ); // Calculate releasable amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); claim.periodsClaimed = claim.periodsClaimed.add(1); } else { break; } } // If there is any amount to release require(amount > 0, "Nothing to release"); // Transfer Tokens from Owner to Beneficiary ERC20(tokenAddress).transfer(claim.beneficiary, amount); claim.amountClaimed = claim.amountClaimed.add(amount); emit Claimed(claim.owner, claim.beneficiary, amount, index); } /** * Get Amount of tokens that can be claimed * * @param index - Index of the Claim */ function claimableAmount(uint256 index) public view returns (uint256) { Claim storage claim = claims[index]; // Calculate Claimable Amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); } else { break; } } return amount; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // TRUFFLE import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract SuperNFTVestStream { using SafeMath for uint256; using Address for address; address public tokenAddress; address public nftAddress; event Claimed( address owner, uint256 nftId, address beneficiary, uint256 amount, uint256 index ); event ClaimCreated( address owner, uint256 nftId, uint256 totalAmount, uint256 index ); struct Claim { address owner; uint256 nftId; uint256[] timePeriods; uint256[] tokenAmounts; uint256 totalAmount; uint256 amountClaimed; uint256 periodsClaimed; } Claim[] private claims; struct StreamInfo { uint256 startTime; bool notOverflow; uint256 startDiff; uint256 diff; uint256 amountPerBlock; uint256[] _timePeriods; uint256[] _tokenAmounts; } mapping(address => uint256[]) private _ownerClaims; mapping(uint256 => uint256[]) private _nftClaims; constructor(address _tokenAddress, address _nftAddress) public { require( _tokenAddress.isContract(), "_tokenAddress must be a contract address" ); require( _nftAddress.isContract(), "_nftAddress must be a contract address" ); tokenAddress = _tokenAddress; nftAddress = _nftAddress; } /** * Get Owner Claims * * @param owner - Claim Owner Address */ function ownerClaims(address owner) external view returns (uint256[] memory) { require(owner != address(0), "Owner address cannot be 0"); return _ownerClaims[owner]; } /** * Get NFT Claims * * @param nftId - NFT ID */ function nftClaims(uint256 nftId) external view returns (uint256[] memory) { require(nftId != 0, "nftId cannot be 0"); return _nftClaims[nftId]; } /** * Get Amount Claimed * * @param index - Claim Index */ function claimed(uint256 index) external view returns (uint256) { return claims[index].amountClaimed; } /** * Get Total Claim Amount * * @param index - Claim Index */ function totalAmount(uint256 index) external view returns (uint256) { return claims[index].totalAmount; } /** * Get Time Periods of Claim * * @param index - Claim Index */ function timePeriods(uint256 index) external view returns (uint256[] memory) { return claims[index].timePeriods; } /** * Get Token Amounts of Claim * * @param index - Claim Index */ function tokenAmounts(uint256 index) external view returns (uint256[] memory) { return claims[index].tokenAmounts; } /** * Create a Claim - To Vest Tokens to NFT * * @param _nftId - Tokens will be claimed by owner of _nftId * @param _startBlock - Block Number to start vesting from * @param _stopBlock - Block Number to end vesting at (Release all tokens) * @param _totalAmount - Total Amount to be Vested * @param _blockTime - Block Time (used for predicting _timePeriods) */ function createClaim( uint256 _nftId, uint256 _startBlock, uint256 _stopBlock, uint256 _totalAmount, uint256 _blockTime ) external returns (bool) { require(_nftId != 0, "Cannot Vest to NFT 0"); require( _stopBlock > _startBlock, "_stopBlock must be greater than _startBlock" ); require(tokenAddress.isContract(), "Invalid tokenAddress"); require(_totalAmount > 0, "Provide Token Amounts to Vest"); require( ERC20(tokenAddress).allowance(msg.sender, address(this)) >= _totalAmount, "Provide token allowance to SuperNFTVestStream contract" ); // Calculate estimated epoch for _startBlock StreamInfo memory streamInfo = StreamInfo(0, false, 0, 0, 0, new uint256[](0), new uint256[](0)); (streamInfo.notOverflow, streamInfo.startDiff) = _startBlock.trySub( block.number ); if (streamInfo.notOverflow) { // If Not Overflow streamInfo.startTime = block.timestamp.add( _blockTime.mul(streamInfo.startDiff) ); } else { // If Overflow streamInfo.startDiff = block.number.sub(_startBlock); streamInfo.startTime = block.timestamp.sub( _blockTime.mul(streamInfo.startDiff) ); } // Calculate _timePeriods & _tokenAmounts streamInfo.diff = _stopBlock.sub(_startBlock); streamInfo.amountPerBlock = _totalAmount.div(streamInfo.diff); streamInfo._timePeriods = new uint256[](streamInfo.diff); streamInfo._tokenAmounts = new uint256[](streamInfo.diff); streamInfo._timePeriods[0] = streamInfo.startTime; streamInfo._tokenAmounts[0] = streamInfo.amountPerBlock; for (uint256 i = 1; i < streamInfo.diff; i++) { streamInfo._timePeriods[i] = streamInfo._timePeriods[i - 1].add( _blockTime ); streamInfo._tokenAmounts[i] = streamInfo.amountPerBlock; } // Transfer Tokens to SuperVestStream ERC20(tokenAddress).transferFrom( msg.sender, address(this), _totalAmount ); // Create Claim Claim memory claim = Claim({ owner: msg.sender, nftId: _nftId, timePeriods: streamInfo._timePeriods, tokenAmounts: streamInfo._tokenAmounts, totalAmount: _totalAmount, amountClaimed: 0, periodsClaimed: 0 }); claims.push(claim); uint256 index = claims.length - 1; // Map Claim Index to Owner & Beneficiary _ownerClaims[msg.sender].push(index); _nftClaims[_nftId].push(index); emit ClaimCreated(msg.sender, _nftId, _totalAmount, index); return true; } /** * Claim Tokens * * @param index - Index of the Claim */ function claim(uint256 index) external { Claim storage claim = claims[index]; // Check if msg.sender is the owner of the NFT require( msg.sender == ERC721(nftAddress).ownerOf(claim.nftId), "msg.sender must own the NFT" ); // Check if anything is left to release require( claim.periodsClaimed < claim.timePeriods.length, "Nothing to release" ); // Calculate releasable amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); claim.periodsClaimed = claim.periodsClaimed.add(1); } else { break; } } // If there is any amount to release require(amount > 0, "Nothing to release"); // Transfer Tokens from Owner to Beneficiary ERC20(tokenAddress).transfer(msg.sender, amount); claim.amountClaimed = claim.amountClaimed.add(amount); emit Claimed(claim.owner, claim.nftId, msg.sender, amount, index); } /** * Get Amount of tokens that can be claimed * * @param index - Index of the Claim */ function claimableAmount(uint256 index) public view returns (uint256) { Claim storage claim = claims[index]; // Calculate Claimable Amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); } else { break; } } return amount; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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.6.2 <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.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // 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.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // TRUFFLE import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract SuperNFTVestCliff { using SafeMath for uint256; using Address for address; address public tokenAddress; address public nftAddress; event Claimed( address owner, uint256 nftId, address beneficiary, uint256 amount, uint256 index ); event ClaimCreated( address owner, uint256 nftId, uint256 totalAmount, uint256 index ); struct Claim { address owner; uint256 nftId; uint256[] timePeriods; uint256[] tokenAmounts; uint256 totalAmount; uint256 amountClaimed; uint256 periodsClaimed; } Claim[] private claims; mapping(address => uint256[]) private _ownerClaims; mapping(uint256 => uint256[]) private _nftClaims; constructor(address _tokenAddress, address _nftAddress) public { require( _tokenAddress.isContract(), "_tokenAddress must be a contract address" ); require( _nftAddress.isContract(), "_nftAddress must be a contract address" ); tokenAddress = _tokenAddress; nftAddress = _nftAddress; } /** * Get Owner Claims * * @param owner - Claim Owner Address */ function ownerClaims(address owner) external view returns (uint256[] memory) { require(owner != address(0), "Owner address cannot be 0"); return _ownerClaims[owner]; } /** * Get NFT Claims * * @param nftId - NFT ID */ function nftClaims(uint256 nftId) external view returns (uint256[] memory) { require(nftId != 0, "nftId cannot be 0"); return _nftClaims[nftId]; } /** * Get Amount Claimed * * @param index - Claim Index */ function claimed(uint256 index) external view returns (uint256) { return claims[index].amountClaimed; } /** * Get Total Claim Amount * * @param index - Claim Index */ function totalAmount(uint256 index) external view returns (uint256) { return claims[index].totalAmount; } /** * Get Time Periods of Claim * * @param index - Claim Index */ function timePeriods(uint256 index) external view returns (uint256[] memory) { return claims[index].timePeriods; } /** * Get Token Amounts of Claim * * @param index - Claim Index */ function tokenAmounts(uint256 index) external view returns (uint256[] memory) { return claims[index].tokenAmounts; } /** * Create a Claim - To Vest Tokens to NFT * * @param _nftId - Tokens will be claimed by owner of _nftId * @param _timePeriods - uint256 Array of Epochs * @param _tokenAmounts - uin256 Array of Amounts to transfer at each time period */ function createClaim( uint256 _nftId, uint256[] memory _timePeriods, uint256[] memory _tokenAmounts ) public returns (bool) { require(_nftId != 0, "Cannot Vest to NFT 0"); require( _timePeriods.length == _tokenAmounts.length, "_timePeriods & _tokenAmounts length mismatch" ); // Calculate total amount uint256 _totalAmount = 0; for (uint256 i = 0; i < _tokenAmounts.length; i++) { _totalAmount = _totalAmount.add(_tokenAmounts[i]); } require(_totalAmount > 0, "Provide Token Amounts to Vest"); require( ERC20(tokenAddress).allowance(msg.sender, address(this)) >= _totalAmount, "Provide token allowance to SuperStreamClaim contract" ); // Transfer Tokens to SuperStreamClaim ERC20(tokenAddress).transferFrom( msg.sender, address(this), _totalAmount ); // Create Claim Claim memory claim = Claim({ owner: msg.sender, nftId: _nftId, timePeriods: _timePeriods, tokenAmounts: _tokenAmounts, totalAmount: _totalAmount, amountClaimed: 0, periodsClaimed: 0 }); claims.push(claim); uint256 index = claims.length.sub(1); // Map Claim Index to Owner & Beneficiary _ownerClaims[msg.sender].push(index); _nftClaims[_nftId].push(index); emit ClaimCreated(msg.sender, _nftId, _totalAmount, index); return true; } /** * Claim Tokens * * @param index - Index of the Claim */ function claim(uint256 index) external { Claim storage claim = claims[index]; // Check if msg.sender is the owner of the NFT require( msg.sender == ERC721(nftAddress).ownerOf(claim.nftId), "msg.sender must own the NFT" ); // Check if anything is left to release require( claim.periodsClaimed < claim.timePeriods.length, "Nothing to release" ); // Calculate releasable amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); claim.periodsClaimed = claim.periodsClaimed.add(1); } else { break; } } // If there is any amount to release require(amount > 0, "Nothing to release"); // Transfer Tokens from Owner to Beneficiary ERC20(tokenAddress).transfer(msg.sender, amount); claim.amountClaimed = claim.amountClaimed.add(amount); emit Claimed(claim.owner, claim.nftId, msg.sender, amount, index); } /** * Get Amount of tokens that can be claimed * * @param index - Index of the Claim */ function claimableAmount(uint256 index) public view returns (uint256) { Claim storage claim = claims[index]; // Calculate Claimable Amount uint256 amount = 0; for ( uint256 i = claim.periodsClaimed; i < claim.timePeriods.length; i++ ) { if (claim.timePeriods[i] <= block.timestamp) { amount = amount.add(claim.tokenAmounts[i]); } else { break; } } return amount; } } pragma solidity ^0.6.2; // REMIX // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/token/ERC721/ERC721.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/token/ERC20/ERC20.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/Counters.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/EnumerableSet.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/math/SafeMath.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/utils/Address.sol"; // TRUFFLE import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; // SuperNFT SMART CONTRACT contract SuperNFT is ERC721 { using EnumerableSet for EnumerableSet.UintSet; using Counters for Counters.Counter; Counters.Counter private _tokenIds; mapping(string => uint8) hashes; /** * Mint + Issue NFT * * @param recipient - NFT will be issued to recipient * @param hash - Artwork IPFS hash * @param data - Artwork URI/Data */ function issueToken( address recipient, string memory hash, string memory data ) public returns (uint256) { require(hashes[hash] != 1); hashes[hash] = 1; _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _mint(recipient, newTokenId); _setTokenURI(newTokenId, data); return newTokenId; } constructor() public ERC721("SUPER NFT", "SNFT") {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; /** @title An OpenSea delegate proxy contract which we include for whitelisting. @author OpenSea */ contract OwnableDelegateProxy { } /** @title An OpenSea proxy registry contract which we include for whitelisting. @author OpenSea */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** @title An ERC-1155 item creation contract which specifies an associated FeeOwner who receives royalties from sales of created items. @author Tim Clancy The fee set by the FeeOwner on this Item is honored by Shop contracts. In addition to the inherited OpenZeppelin dependency, this uses ideas from the original ERC-1155 reference implementation. */ contract Fee1155NFT is ERC1155, Ownable { using SafeMath for uint256; /// A version number for this fee-bearing 1155 item contract's interface. uint256 public version = 1; /// The ERC-1155 URI for looking up item metadata using {id} substitution. string public metadataUri; /// A user-specified FeeOwner to receive a portion of item sale earnings. FeeOwner public feeOwner; /// Specifically whitelist an OpenSea proxy registry address. address public proxyRegistryAddress; /// A counter to enforce unique IDs for each item group minted. uint256 public nextItemGroupId; /// This mapping tracks the number of unique items within each item group. mapping (uint256 => uint256) public itemGroupSizes; /// An event for tracking the creation of an item group. event ItemGroupCreated(uint256 itemGroupId, uint256 itemGroupSize, address indexed creator); /** Construct a new ERC-1155 item with an associated FeeOwner fee. @param _uri The metadata URI to perform token ID substitution in. @param _feeOwner The address of a FeeOwner who receives earnings from this item. */ constructor(string memory _uri, FeeOwner _feeOwner, address _proxyRegistryAddress) public ERC1155(_uri) { metadataUri = _uri; feeOwner = _feeOwner; proxyRegistryAddress = _proxyRegistryAddress; nextItemGroupId = 0; } /** An override to whitelist the OpenSea proxy contract to enable gas-free listings. This function returns true if `_operator` is approved to transfer items owned by `_owner`. @param _owner The owner of items to check for transfer ability. @param _operator The potential transferrer of `_owner`'s items. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** Allow the item owner to update the metadata URI of this collection. @param _uri The new URI to update to. */ function setURI(string calldata _uri) external onlyOwner { metadataUri = _uri; } /** Create a new NFT item group of a specific size. NFTs within a group share a group ID in the upper 128-bits of their full item ID. Within a group NFTs can be distinguished for the purposes of serializing issue numbers. @param recipient The address to receive all NFTs within the newly-created group. @param groupSize The number of individual NFTs to create within the group. @param data Any associated data to use on items minted in this transaction. */ function createNFT(address recipient, uint256 groupSize, bytes calldata data) external onlyOwner returns (uint256) { require(groupSize > 0, "You cannot create an empty item group."); // Create an item group of requested size using the next available ID. uint256 shiftedGroupId = nextItemGroupId << 128; itemGroupSizes[shiftedGroupId] = groupSize; // Record the supply cap of each item being created in the group. uint256[] memory itemIds = new uint256[](groupSize); uint256[] memory amounts = new uint256[](groupSize); for (uint256 i = 1; i <= groupSize; i++) { itemIds[i - 1] = shiftedGroupId.add(i); amounts[i - 1] = 1; } // Mint the entire batch of items. _mintBatch(recipient, itemIds, amounts, data); // Increment our next item group ID and return our created item group ID. nextItemGroupId = nextItemGroupId.add(1); emit ItemGroupCreated(shiftedGroupId, groupSize, msg.sender); return shiftedGroupId; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeOwner.sol"; import "./Fee1155.sol"; import "./Staker.sol"; /** @title A simple Shop contract for selling ERC-1155s for points, Ether, or ERC-20 tokens. @author Tim Clancy This contract allows its owner to list NFT items for sale. NFT items are purchased by users using points spent on a corresponding Staker contract. The Shop must be approved by the owner of the Staker contract. */ contract Shop1155 is ERC1155Holder, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// A version number for this Shop contract's interface. uint256 public version = 1; /// A user-specified, descriptive name for this Shop. string public name; /// A user-specified FeeOwner to receive a portion of Shop earnings. FeeOwner public feeOwner; /// A user-specified Staker contract to spend user points on. Staker[] public stakers; /** This struct tracks information about a single asset with associated price that an item is being sold in the shop for. @param assetType A sentinel value for the specific type of asset being used. 0 = non-transferrable points from a Staker; see `asset`. 1 = Ether. 2 = an ERC-20 token, see `asset`. @param asset Some more specific information about the asset to charge in. If the `assetType` is 0, we convert the given address to an integer index for finding a specific Staker from `stakers`. If the `assetType` is 1, we ignore this field. If the `assetType` is 2, we use this address to find the ERC-20 token that we should be specifically charging with. @param price The amount of the specified `assetType` and `asset` to charge. */ struct PricePair { uint256 assetType; address asset; uint256 price; } /** This struct tracks information about each item of inventory in the Shop. @param token The address of a Fee1155 collection contract containing the item we want to sell. @param id The specific ID of the item within the Fee1155 from `token`. @param amount The amount of this specific item on sale in the Shop. */ struct ShopItem { Fee1155 token; uint256 id; uint256 amount; } // The Shop's inventory of items for sale. uint256 nextItemId; mapping (uint256 => ShopItem) public inventory; mapping (uint256 => uint256) public pricePairLengths; mapping (uint256 => mapping (uint256 => PricePair)) public prices; /** Construct a new Shop by providing it a name, FeeOwner, optional Stakers. Any attached Staker contracts must also approve this Shop to spend points. @param _name The name of the Shop contract. @param _feeOwner The address of the FeeOwner due a portion of Shop earnings. @param _stakers The addresses of any Stakers to permit spending points from. */ constructor(string memory _name, FeeOwner _feeOwner, Staker[] memory _stakers) public { name = _name; feeOwner = _feeOwner; stakers = _stakers; nextItemId = 0; } /** Returns the length of the Staker array. @return the length of the Staker array. */ function getStakerCount() external view returns (uint256) { return stakers.length; } /** Returns the number of items in the Shop's inventory. @return the number of items in the Shop's inventory. */ function getInventoryCount() external view returns (uint256) { return nextItemId; } /** Allows the Shop owner to add newly-supported Stakers for point spending. @param _stakers The array of new Stakers to add. */ function addStakers(Staker[] memory _stakers) external onlyOwner { for (uint256 i = 0; i < _stakers.length; i++) { stakers.push(_stakers[i]); } } /** Allows the Shop owner to list a new set of NFT items for sale. @param _pricePairs The asset address to price pairings to use for selling each item. @param _items The array of Fee1155 item contracts to sell from. @param _ids The specific Fee1155 item IDs to sell. @param _amounts The amount of inventory being listed for each item. */ function listItems(PricePair[] memory _pricePairs, Fee1155[] calldata _items, uint256[][] calldata _ids, uint256[][] calldata _amounts) external nonReentrant onlyOwner { require(_items.length > 0, "You must list at least one item."); require(_items.length == _ids.length, "Items length cannot be mismatched with IDs length."); require(_items.length == _amounts.length, "Items length cannot be mismatched with amounts length."); // Iterate through every specified Fee1155 contract to list items. for (uint256 i = 0; i < _items.length; i++) { Fee1155 item = _items[i]; uint256[] memory ids = _ids[i]; uint256[] memory amounts = _amounts[i]; require(ids.length > 0, "You must specify at least one item ID."); require(ids.length == amounts.length, "Item IDs length cannot be mismatched with amounts length."); // For each Fee1155 contract, add the requested item IDs to the Shop. for (uint256 j = 0; j < ids.length; j++) { uint256 id = ids[j]; uint256 amount = amounts[j]; require(amount > 0, "You cannot list an item with no starting amount."); inventory[nextItemId + j] = ShopItem({ token: item, id: id, amount: amount }); for (uint k = 0; k < _pricePairs.length; k++) { prices[nextItemId + j][k] = _pricePairs[k]; } pricePairLengths[nextItemId + j] = _pricePairs.length; } nextItemId = nextItemId.add(ids.length); // Batch transfer the listed items to the Shop contract. item.safeBatchTransferFrom(msg.sender, address(this), ids, amounts, ""); } } /** Allows the Shop owner to remove items. @param _itemId The id of the specific inventory item of this shop to remove. @param _amount The amount of the specified item to remove. */ function removeItem(uint256 _itemId, uint256 _amount) external nonReentrant onlyOwner { ShopItem storage item = inventory[_itemId]; require(item.amount >= _amount && item.amount != 0, "There is not enough of your desired item to remove."); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); } /** Allows the Shop owner to adjust the prices of an NFT item set. @param _itemId The id of the specific inventory item of this shop to adjust. @param _pricePairs The asset-price pairs at which to sell a single instance of the item. */ function changeItemPrice(uint256 _itemId, PricePair[] memory _pricePairs) external onlyOwner { for (uint i = 0; i < _pricePairs.length; i++) { prices[_itemId][i] = _pricePairs[i]; } pricePairLengths[_itemId] = _pricePairs.length; } /** Allows any user to purchase an item from this Shop provided they have enough of the asset being used to purchase with. @param _itemId The ID of the specific inventory item of this shop to buy. @param _amount The amount of the specified item to purchase. @param _assetId The index of the asset from the item's asset-price pairs to attempt this purchase using. */ function purchaseItem(uint256 _itemId, uint256 _amount, uint256 _assetId) external nonReentrant payable { ShopItem storage item = inventory[_itemId]; require(item.amount >= _amount && item.amount != 0, "There is not enough of your desired item in stock to purchase."); require(_assetId < pricePairLengths[_itemId], "Your specified asset ID is not valid."); PricePair memory sellingPair = prices[_itemId][_assetId]; // If the sentinel value for the point asset type is found, sell for points. // This involves converting the asset from an address to a Staker index. if (sellingPair.assetType == 0) { uint256 stakerIndex = uint256(sellingPair.asset); stakers[stakerIndex].spendPoints(msg.sender, sellingPair.price.mul(_amount)); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); // If the sentinel value for the Ether asset type is found, sell for Ether. } else if (sellingPair.assetType == 1) { uint256 etherPrice = sellingPair.price.mul(_amount); require(msg.value >= etherPrice, "You did not send enough Ether to complete this purchase."); uint256 feePercent = feeOwner.fee(); uint256 feeValue = msg.value.mul(feePercent).div(100000); uint256 itemRoyaltyPercent = item.token.feeOwner().fee(); uint256 royaltyValue = msg.value.mul(itemRoyaltyPercent).div(100000); (bool success, ) = payable(feeOwner.owner()).call{ value: feeValue }(""); require(success, "Platform fee transfer failed."); (success, ) = payable(item.token.feeOwner().owner()).call{ value: royaltyValue }(""); require(success, "Creator royalty transfer failed."); (success, ) = payable(owner()).call{ value: msg.value.sub(feeValue).sub(royaltyValue) }(""); require(success, "Shop owner transfer failed."); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); // Otherwise, attempt to sell for an ERC20 token. } else { IERC20 sellingAsset = IERC20(sellingPair.asset); uint256 tokenPrice = sellingPair.price.mul(_amount); require(sellingAsset.balanceOf(msg.sender) >= tokenPrice, "You do not have enough token to complete this purchase."); uint256 feePercent = feeOwner.fee(); uint256 feeValue = tokenPrice.mul(feePercent).div(100000); uint256 itemRoyaltyPercent = item.token.feeOwner().fee(); uint256 royaltyValue = tokenPrice.mul(itemRoyaltyPercent).div(100000); sellingAsset.safeTransferFrom(msg.sender, feeOwner.owner(), feeValue); sellingAsset.safeTransferFrom(msg.sender, item.token.feeOwner().owner(), royaltyValue); sellingAsset.safeTransferFrom(msg.sender, owner(), tokenPrice.sub(feeValue).sub(royaltyValue)); inventory[_itemId].amount = inventory[_itemId].amount.sub(_amount); item.token.safeTransferFrom(address(this), msg.sender, item.id, _amount, ""); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./FeeOwner.sol"; import "./Shop1155.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Shops. @author Tim Clancy This is the governing registry of all SuperFarm Shop assets. */ contract FarmShopRecords is Ownable, ReentrancyGuard { /// A version number for this record contract's interface. uint256 public version = 1; /// The current platform fee owner to force when creating Shops. FeeOwner public platformFeeOwner; /// A mapping for an array of all Shop1155s deployed by a particular address. mapping (address => address[]) public shopRecords; /// An event for tracking the creation of a new Shop. event ShopCreated(address indexed shopAddress, address indexed creator); /** Construct a new registry of SuperFarm records with a specified platform fee owner. @param _feeOwner The address of the FeeOwner due a portion of all Shop earnings. */ constructor(FeeOwner _feeOwner) public { platformFeeOwner = _feeOwner; } /** Allows the registry owner to update the platform FeeOwner to use upon Shop creation. @param _feeOwner The address of the FeeOwner to make the new platform fee owner. */ function changePlatformFeeOwner(FeeOwner _feeOwner) external onlyOwner { platformFeeOwner = _feeOwner; } /** Create a Shop1155 on behalf of the owner calling this function. The Shop supports immediately registering attached Stakers if provided. @param _name The name of the Shop to create. @param _stakers An array of Stakers to attach to the new Shop. */ function createShop(string calldata _name, Staker[] calldata _stakers) external nonReentrant returns (Shop1155) { Shop1155 newShop = new Shop1155(_name, platformFeeOwner, _stakers); // Transfer ownership of the new Shop to the user then store a reference. newShop.transferOwnership(msg.sender); address shopAddress = address(newShop); shopRecords[msg.sender].push(shopAddress); emit ShopCreated(shopAddress, msg.sender); return newShop; } /** Get the number of entries in the Shop records mapping for the given user. @return The number of Shops added for a given address. */ function getShopCount(address _user) external view returns (uint256) { return shopRecords[_user].length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./Token.sol"; /** @title A basic smart contract for tracking the ownership of SuperFarm Tokens. @author Tim Clancy This is the governing registry of all SuperFarm Token assets. */ contract FarmTokenRecords is Ownable, ReentrancyGuard { /// A version number for this record contract's interface. uint256 public version = 1; /// A mapping for an array of all Tokens deployed by a particular address. mapping (address => address[]) public tokenRecords; /// An event for tracking the creation of a new Token. event TokenCreated(address indexed tokenAddress, address indexed creator); /** Create a Token on behalf of the owner calling this function. The Token supports immediate minting at the time of creation to particular addresses. @param _name The name of the Token to create. @param _ticker The ticker symbol of the Token to create. @param _cap The supply cap of the Token. @param _directMintAddresses An array of addresses to mint directly to. @param _directMintAmounts An array of Token amounts to mint to keyed addresses. */ function createToken(string calldata _name, string calldata _ticker, uint256 _cap, address[] calldata _directMintAddresses, uint256[] calldata _directMintAmounts) external nonReentrant returns (Token) { require(_directMintAddresses.length == _directMintAmounts.length, "Direct mint addresses length cannot be mismatched with mint amounts length."); // Create the token and optionally mint any specified addresses. Token newToken = new Token(_name, _ticker, _cap); for (uint256 i = 0; i < _directMintAddresses.length; i++) { address directMintAddress = _directMintAddresses[i]; uint256 directMintAmount = _directMintAmounts[i]; newToken.mint(directMintAddress, directMintAmount); } // Transfer ownership of the new Token to the user then store a reference. newToken.transferOwnership(msg.sender); address tokenAddress = address(newToken); tokenRecords[msg.sender].push(tokenAddress); emit TokenCreated(tokenAddress, msg.sender); return newToken; } /** Allow a user to add an existing Token contract to the registry. @param _tokenAddress The address of the Token contract to add for this user. */ function addToken(address _tokenAddress) external { tokenRecords[msg.sender].push(_tokenAddress); } /** Get the number of entries in the Token records mapping for the given user. @return The number of Tokens added for a given address. */ function getTokenCount(address _user) external view returns (uint256) { return tokenRecords[_user].length; } } // SPDX-License-Identifier: BSD-3-Clause // Modified from https://github.com/compound-finance/compound-protocol/blob/master/contracts/Timelock.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; } receive() external payable { } function setDelay(uint 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, uint value, string memory signature, bytes memory data, uint 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, uint value, string memory signature, bytes memory data, uint 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 _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return 'Transaction reverted silently'; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint 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 (uint) { return block.timestamp; } }
/ Iterate through every specified item to make an offer on items. Record an offer for this item.
Shop owner. This function takes a user's Ether into escrow for the offer. @param _itemGroupIds An array of (unique) item groups for a user to place an offer for. function makeOffers(uint256[] calldata _itemGroupIds) public nonReentrant payable { require(_itemGroupIds.length > 0, "You must make an offer for at least one item group."); for (uint256 i = 0; i < _itemGroupIds.length; i++) { uint256 groupId = _itemGroupIds[i]; uint256 price = prices[groupId]; require(price > 0, "You cannot make an offer for an item that is not listed."); bidders[groupId].push(msg.sender); offers[groupId][msg.sender] = msg.value; } }
1,271,999
[ 1, 19, 11436, 3059, 3614, 1269, 761, 358, 1221, 392, 10067, 603, 1516, 18, 5059, 392, 10067, 364, 333, 761, 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 ]
[ 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, 17568, 3410, 18, 1220, 445, 5530, 279, 729, 1807, 512, 1136, 1368, 2904, 492, 364, 326, 10067, 18, 203, 203, 565, 632, 891, 389, 1726, 1114, 2673, 1922, 526, 434, 261, 6270, 13, 761, 3252, 364, 279, 729, 358, 3166, 392, 10067, 364, 18, 203, 225, 445, 1221, 7210, 414, 12, 11890, 5034, 8526, 745, 892, 389, 1726, 1114, 2673, 13, 1071, 1661, 426, 8230, 970, 8843, 429, 288, 203, 565, 2583, 24899, 1726, 1114, 2673, 18, 2469, 405, 374, 16, 203, 1377, 315, 6225, 1297, 1221, 392, 10067, 364, 622, 4520, 1245, 761, 1041, 1199, 1769, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 1726, 1114, 2673, 18, 2469, 31, 277, 27245, 288, 203, 1377, 2254, 5034, 6612, 273, 389, 1726, 1114, 2673, 63, 77, 15533, 203, 1377, 2254, 5034, 6205, 273, 19827, 63, 27547, 15533, 203, 1377, 2583, 12, 8694, 405, 374, 16, 203, 3639, 315, 6225, 2780, 1221, 392, 10067, 364, 392, 761, 716, 353, 486, 12889, 1199, 1769, 203, 203, 1377, 324, 1873, 414, 63, 27547, 8009, 6206, 12, 3576, 18, 15330, 1769, 203, 1377, 28641, 63, 27547, 6362, 3576, 18, 15330, 65, 273, 1234, 18, 1132, 31, 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 ]
./partial_match/1/0xdf3ac4F479375802A821f7b7b46Cd7EB5E4262cC/sources/contracts/lybra/token/EUSD.sol
* @notice Moves `_amount` tokens from `_sender` to `_recipient`. Emits a `Transfer` event. Emits a `TransferShares` event./
function _transfer(address _sender, address _recipient, uint256 _amount) internal { uint256 _sharesToTransfer = getSharesByMintedEUSD(_amount); _transferShares(_sender, _recipient, _sharesToTransfer); emit Transfer(_sender, _recipient, _amount); emit TransferShares(_sender, _recipient, _sharesToTransfer); }
2,701,804
[ 1, 19297, 1375, 67, 8949, 68, 2430, 628, 1375, 67, 15330, 68, 358, 1375, 67, 20367, 8338, 7377, 1282, 279, 1375, 5912, 68, 871, 18, 7377, 1282, 279, 1375, 5912, 24051, 68, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 389, 15330, 16, 1758, 389, 20367, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 389, 30720, 774, 5912, 273, 1322, 3395, 455, 858, 49, 474, 329, 41, 3378, 40, 24899, 8949, 1769, 203, 3639, 389, 13866, 24051, 24899, 15330, 16, 389, 20367, 16, 389, 30720, 774, 5912, 1769, 203, 3639, 3626, 12279, 24899, 15330, 16, 389, 20367, 16, 389, 8949, 1769, 203, 3639, 3626, 12279, 24051, 24899, 15330, 16, 389, 20367, 16, 389, 30720, 774, 5912, 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 ]
pragma solidity ^0.6.0; import "../node_modules/@openzeppelin/contracts/access/AccessControl.sol"; import "../node_modules/@openzeppelin/contracts/GSN/Context.sol"; import "../node_modules/@openzeppelin/contracts/math/SafeMath.sol"; import "./VoteNFT.sol"; contract Elections is Context, AccessControl, VoteNFT { using SafeMath for uint256; string constant TOKEN_URI = "https://ropsten.etherscan.io/tx/"; uint internal electionCount; // OpenZeppelin access control bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant VOTER_ROLE = keccak256("VOTER_ROLE"); // Events event NewElection(uint eid, uint deadline); event VoterRegistered(address indexed registeredVoter, uint electionID); event NewVoterRequest(address indexed newVoter); event Voted(uint propNumber, uint eid, address indexed voter, uint256 newNFT); event Delegated(address indexed delegate, uint eid, address indexed voter); event ChangedVote(uint propNumber, uint eid, address indexed voter); struct Voter { uint weight; // weight is accumulated by delegation bool voted; // if true, that person already voted bool registered; // need to register for each election bool hasChangedVote; // user can change vote only once address delegate; // person delegated to uint vote; // index of the voted proposal } struct Proposal { string name; // short name uint voteCount; // number of accumulated votes } struct Election { mapping(address => Voter) voters; Proposal[] proposals; uint deadline; } // stores an `Election` struct to an election ID mapping(uint => Election) public elections; // Assign admin and voter role to msg.sender constructor() public { _setupRole(ADMIN_ROLE, _msgSender()); _setupRole(VOTER_ROLE, _msgSender()); _setRoleAdmin(VOTER_ROLE, ADMIN_ROLE); //sets admin role in charge of voter role } modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, _msgSender()), "DOES_NOT_HAVE_ADMIN_ROLE"); _; } modifier onlyVoter() { require(hasRole(VOTER_ROLE, _msgSender()), "DOES_NOT_HAVE_VOTER_ROLE"); _; } /** * @dev Admin creates new election with two competing proposals * @param proposal1 string or hash describing proposal or candidate * @param proposal2 string or hash describing proposal or candidate */ function newElection(string memory proposal1, string memory proposal2, uint dl) public onlyAdmin { uint electionID = electionCount + 1; Election storage e = elections[electionID]; e.voters[_msgSender()].weight = 1; e.voters[_msgSender()].registered = true; e.proposals.push(Proposal({name: proposal1, voteCount: 0})); e.proposals.push(Proposal({name: proposal2, voteCount: 0})); e.deadline = dl; emit NewElection(electionID, dl); electionCount++; } /** * @dev Public function allowing users to request for admin to register their address */ function requestAccess() public { require(!hasRole(VOTER_ROLE, _msgSender()), "ALREADY_HAS_VOTER_ROLE"); emit NewVoterRequest(_msgSender()); } /** * @dev Give `voter` the right to vote and register for elections * @param voter address to grant voting access */ function registerToVote(address voter) public onlyAdmin { require(!hasRole(VOTER_ROLE, voter), "ALREADY_HAS_VOTER_ROLE"); _setupRole(VOTER_ROLE, voter); } /** * @dev Revoke registered `voter` from participating in elections * @param voter address being revoked voting access */ function revokeVoter(address voter) public onlyAdmin { require(hasRole(VOTER_ROLE, voter), "VOTER_MUST_ALREADY_HAVE_ROLE"); revokeRole(VOTER_ROLE, voter); } /** * @dev Voter with `VOTER_ROLE` self registers for a given election * @param electionID ID for the election the voter wants to vote in */ function registerForElection(uint electionID) public onlyVoter { Election storage e = elections[electionID]; require(!e.voters[_msgSender()].registered, "VOTER_ALREADY_REGISTERED"); require(block.timestamp < e.deadline, "Voting deadline has expired"); e.voters[_msgSender()].weight += 1; e.voters[_msgSender()].registered = true; emit VoterRegistered(_msgSender(), electionID); } /** * @dev Delegate to `to` the weight of another valid voter's vote * @param to delegate address * @param electionID ID of election in which voter is delegating their vote */ function delegateVote(address to, uint electionID) public onlyVoter { // Check that addr delegate has right to vote require(hasRole(VOTER_ROLE, to), "DOES_NOT_HAVE_VOTER_ROLE"); Election storage e = elections[electionID]; Voter storage sender = e.voters[_msgSender()]; require(!sender.voted, "Address has already voted"); // Forward the delegation if `to` also delegated. while (e.voters[to].delegate != address(0) && e.voters[to].delegate != _msgSender()) { to = e.voters[to].delegate; } require(to != _msgSender(), "Delegation can not be to self"); // Update `sender` sender.voted = true; sender.delegate = to; Voter storage delegate = e.voters[to]; if (delegate.voted) { // If delegate already voted, directly add to the number of votes e.proposals[delegate.vote].voteCount += sender.weight; // Add sender weight to delegate as well in case delegate changes vote delegate.weight += sender.weight; // Emit `Voted` event since Delegate has already voted; no NFT rewarded for delegation emit Voted(delegate.vote, electionID, _msgSender(), 0); } else { // If delegate did not vote yet, add to weight. delegate.weight += sender.weight; emit Delegated(sender.delegate, electionID, _msgSender()); } } /** * @dev Vote on a given proposal * @param proposal number of proposal * @param electionID ID of election in which voter is delegating their vote */ function vote(uint proposal, uint electionID) public onlyVoter { // Only two choices in the election require(proposal < 2, "Invalid proposal number"); Election storage e = elections[electionID]; require(block.timestamp < e.deadline, "Voting deadline has expired"); Voter storage sender = e.voters[_msgSender()]; require(!sender.voted, "Address has already voted"); require(sender.registered, "Voter must register for each election"); sender.voted = true; sender.vote = proposal; e.proposals[proposal].voteCount += sender.weight; //Reward proposer with NFT uint256 NFT_ID = awardItem(_msgSender(), TOKEN_URI); emit Voted(proposal, electionID, _msgSender(), NFT_ID); } /** * @dev Change your vote to a different proposal, may only be executed once per user * @param proposal number of proposal, must not be same as previous vote * @param electionID ID of election in which voter is delegating their vote */ function changeVote(uint proposal, uint electionID) public onlyVoter { // Only two choices in the election require(proposal < 2, "Invalid proposal number"); Election storage e = elections[electionID]; Voter storage sender = e.voters[_msgSender()]; require(sender.voted, "Address must have already voted"); require(!sender.hasChangedVote, "Voter can only change vote once"); require(sender.vote != proposal, "New proposal is same as current vote"); require(sender.delegate == address(0), "Voter must not have delegated"); //require(sender.weight == 1, "Delegates may not change vote"); Uncomment if applicable // Remove vote from old proposal uint oldProposal = sender.vote; e.proposals[oldProposal].voteCount -= sender.weight; // Add vote to new proposal sender.vote = proposal; e.proposals[proposal].voteCount += sender.weight; sender.hasChangedVote = true; emit ChangedVote(proposal, electionID, _msgSender()); } /** * @dev Computes then returns the winning proposal, taking all previous votes into account. * @param electionID ID of election */ function winningProposal(uint electionID) internal view returns (uint) { Election storage e = elections[electionID]; // uint winningVoteCount = 0; // uint wProposal; uint prop0 = e.proposals[0].voteCount; uint prop1 = e.proposals[1].voteCount; if (prop0 > prop1){ return 0; } else if (prop1 > prop0) { return 1; } else { // it's a tie return 2; } } /** * @dev Calls winningProposal() function to get the index of winner and then returns the name * @param electionID ID of election */ function winnerName(uint electionID) public view returns (string memory) { Election storage e = elections[electionID]; require(block.timestamp > e.deadline, "Have not reached election deadline"); uint result = winningProposal(electionID); if (result != 2) { return e.proposals[result].name; } else { return "TIE"; } } /** * @dev Gets current state of a voter * @return uint TODO * @param electionID ID of election * @param voter voter address */ function getVoterInfo(uint electionID, address voter) public view returns (uint, bool, bool, bool, address, uint) { Election storage e = elections[electionID]; return (e.voters[voter].weight, e.voters[voter].voted, e.voters[voter].registered, e.voters[voter].hasChangedVote, e.voters[voter].delegate, e.voters[voter].vote); } /** * @dev Gets current state of an election * @return uint TODO * @param electionID ID of election */ function getElectionInfo(uint electionID) public view returns (string memory, uint, string memory, uint, uint) { Election storage e = elections[electionID]; return (e.proposals[0].name, e.proposals[0].voteCount, e.proposals[1].name, e.proposals[1].voteCount, e.deadline); } }
* @dev Vote on a given proposal @param proposal number of proposal @param electionID ID of election in which voter is delegating their vote/ Only two choices in the electionReward proposer with NFT
function vote(uint proposal, uint electionID) public onlyVoter { require(proposal < 2, "Invalid proposal number"); Election storage e = elections[electionID]; require(block.timestamp < e.deadline, "Voting deadline has expired"); Voter storage sender = e.voters[_msgSender()]; require(!sender.voted, "Address has already voted"); require(sender.registered, "Voter must register for each election"); sender.voted = true; sender.vote = proposal; e.proposals[proposal].voteCount += sender.weight; uint256 NFT_ID = awardItem(_msgSender(), TOKEN_URI); emit Voted(proposal, electionID, _msgSender(), NFT_ID); }
12,604,967
[ 1, 19338, 603, 279, 864, 14708, 225, 14708, 1300, 434, 14708, 225, 25526, 734, 1599, 434, 25526, 316, 1492, 331, 20005, 353, 11158, 1776, 3675, 12501, 19, 5098, 2795, 7246, 316, 326, 25526, 17631, 1060, 450, 5607, 598, 423, 4464, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12501, 12, 11890, 14708, 16, 2254, 25526, 734, 13, 1071, 1338, 58, 20005, 288, 203, 3639, 2583, 12, 685, 8016, 411, 576, 16, 315, 1941, 14708, 1300, 8863, 203, 3639, 512, 942, 2502, 425, 273, 25526, 87, 63, 292, 794, 734, 15533, 203, 3639, 2583, 12, 2629, 18, 5508, 411, 425, 18, 22097, 1369, 16, 315, 58, 17128, 14096, 711, 7708, 8863, 203, 3639, 776, 20005, 2502, 5793, 273, 425, 18, 90, 352, 414, 63, 67, 3576, 12021, 1435, 15533, 203, 3639, 2583, 12, 5, 15330, 18, 90, 16474, 16, 315, 1887, 711, 1818, 331, 16474, 8863, 203, 3639, 2583, 12, 15330, 18, 14327, 16, 315, 58, 20005, 1297, 1744, 364, 1517, 25526, 8863, 203, 540, 203, 3639, 5793, 18, 90, 16474, 273, 638, 31, 203, 3639, 5793, 18, 25911, 273, 14708, 31, 203, 203, 3639, 425, 18, 685, 22536, 63, 685, 8016, 8009, 25911, 1380, 1011, 5793, 18, 4865, 31, 203, 3639, 2254, 5034, 423, 4464, 67, 734, 273, 279, 2913, 1180, 24899, 3576, 12021, 9334, 14275, 67, 3098, 1769, 203, 3639, 3626, 776, 16474, 12, 685, 8016, 16, 25526, 734, 16, 389, 3576, 12021, 9334, 423, 4464, 67, 734, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.4.16 <0.9.0; /** @title Contract that faciliate the voting of Star Wars Characters */ contract StarWarsPoll { //Total Number of Characters in the Poll uint256 private _totalCharacters; // Read/write mapping(address => bool) private _addressVoted; //Address and has voted //Read/write mapping(uint256 => uint256) private _candidates; //Id and vote count constructor() public { _totalCharacters = 0; } /** @dev Casts a vote for a star wars character based on thier id @param _id The id of the Star wars character */ function castVote(uint256 _id) external { //Checking that the address has not voted before require(!_addressVoted[msg.sender], "This address has already voted"); //Get the mapping of the id and vote count _candidates[_id]++; //Setting the address value to voted _addressVoted[msg.sender] = true; } /** @dev Checks if the account has already voted @return Returns a boolean value based on if the account has already made a vote */ function hasAddressVoted() external view returns (bool) { return _addressVoted[msg.sender]; } /** @dev Gets vote count of each character @return An array with each characters vote count */ function getAll() external view returns (uint[] memory) { require(_totalCharacters != 0,"There are no characters to vote for in the pool"); uint[] memory ret = new uint[](_totalCharacters); for (uint256 i = 0; i < _totalCharacters; i++) { ret[i] = _candidates[i]; } return ret; } /** @dev Sets the total number of charactesr in the poll @param _numCharacters The number of characters in the poll */ function setTotalCharacters(uint256 _numCharacters) external { require( _numCharacters != _totalCharacters, "The Amount of Characters Is already set at the value entered" ); //Setting the number of characters in the poll _totalCharacters = _numCharacters; } /** @dev Gets the total amount of characters in the poll @return returns a uint representing the total amount of charcters */ function getTotalCharacters() external view returns (uint256) { return _totalCharacters; } }
/Setting the number of characters in the poll
function setTotalCharacters(uint256 _numCharacters) external { require( _numCharacters != _totalCharacters, "The Amount of Characters Is already set at the value entered" ); _totalCharacters = _numCharacters; } @return returns a uint representing the total amount of charcters
13,138,527
[ 1, 19, 5568, 326, 1300, 434, 3949, 316, 326, 7672, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25015, 11600, 12, 11890, 5034, 389, 2107, 11600, 13, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 389, 2107, 11600, 480, 389, 4963, 11600, 16, 203, 5411, 315, 1986, 16811, 434, 3703, 9202, 2585, 1818, 444, 622, 326, 460, 16219, 6, 203, 3639, 11272, 203, 203, 3639, 389, 4963, 11600, 273, 389, 2107, 11600, 31, 203, 565, 289, 203, 203, 565, 632, 2463, 1135, 279, 2254, 5123, 326, 2078, 3844, 434, 1149, 299, 414, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x2b28688e290aF66Fbf67280937399140B5F1Dda3/sources/BerryMaster.sol
* @dev Gets the a value for the latest timestamp available @return value for timestamp of last proof of work submited @return true if the is a timestamp for the lastNewValue/
function getLastNewValue() external view returns (uint256, bool) { return berry.getLastNewValue(); }
11,057,050
[ 1, 3002, 326, 279, 460, 364, 326, 4891, 2858, 2319, 327, 460, 364, 2858, 434, 1142, 14601, 434, 1440, 4879, 329, 327, 638, 309, 326, 353, 279, 2858, 364, 326, 1142, 1908, 620, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7595, 1908, 620, 1435, 3903, 1476, 1135, 261, 11890, 5034, 16, 1426, 13, 288, 203, 3639, 327, 324, 21938, 18, 588, 3024, 1908, 620, 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 ]
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( ) public { totalSupply = 100000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name ="Love Wine Coin"; // Set the name for display purposes symbol = "LOVC"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ // function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // require(_value <= allowance[_from][msg.sender]); // Check allowance // allowance[_from][msg.sender] -= _value; // _transfer(_from, _to, _value); // return true; // } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ // function approve(address _spender, uint256 _value) public // returns (bool success) { // allowance[msg.sender][_spender] = _value; // return true; // } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ // function approveAndCall(address _spender, uint256 _value, bytes _extraData) // public // returns (bool success) { // tokenRecipient spender = tokenRecipient(_spender); // if (approve(_spender, _value)) { // spender.receiveApproval(msg.sender, _value, this, _extraData); // return true; // } // } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ // function burn(uint256 _value) public returns (bool success) { // require(balanceOf[msg.sender] >= _value); // Check if the sender has enough // balanceOf[msg.sender] -= _value; // Subtract from the sender // totalSupply -= _value; // Updates totalSupply // Burn(msg.sender, _value); // return true; // } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ // function burnFrom(address _from, uint256 _value) public returns (bool success) { // require(balanceOf[_from] >= _value); // Check if the targeted balance is enough // require(_value <= allowance[_from][msg.sender]); // Check allowance // balanceOf[_from] -= _value; // Subtract from the targeted balance // allowance[_from][msg.sender] -= _value; // Subtract from the sender&#39;s allowance // totalSupply -= _value; // Update totalSupply // Burn(_from, _value); // return true; // } }
Update total supply with the decimal amount
totalSupply = 100000000000 * 10 ** uint256(decimals);
10,840,284
[ 1, 1891, 2078, 14467, 598, 326, 6970, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 3088, 1283, 273, 225, 15088, 11706, 380, 1728, 2826, 2254, 5034, 12, 31734, 1769, 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 ]
./partial_match/1/0x0ded7fAf50DB3bb369fD87f9ec7558d7e7cDd6c4/sources/APU.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 { Welcome, function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
15,527,060
[ 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, 59, 16312, 16, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: WTFPL pragma solidity 0.8.12; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../BaseIDO.sol"; /** * @notice In this IDO, the `asset` *MUST* conform to `IERC721`. */ abstract contract BaseERC721IDO is BaseIDO { constructor(address _owner, Config memory config) BaseIDO(_owner, config) { // Empty } function _updateConfig(Config memory config) internal virtual override { require(config.softCap == 0, "DAOKIT: INVALID_SOFT_CAP"); require(config.hardCap == 0, "DAOKIT: INVALID_HARD_CAP"); require(config.individualCap == 0, "DAOKIT: INVALID_INDIVIDUAL_CAP"); super._updateConfig(config); } /** * @notice Transfers `asset`s of `tokenIds` to `to` address from `this` contract. Parameter `amounts` is ignored. */ function _offerAssets( address to, uint256[] memory tokenIds, uint256[] memory ) internal virtual override { address _asset = asset; for (uint256 i; i < tokenIds.length; i++) { IERC721(_asset).safeTransferFrom(address(this), to, tokenIds[i]); } } /** * @notice Transfers all balance of ERC721 `asset` from `this` contract to `owner` */ function _returnAssets(uint256[] memory tokenIds) internal virtual override { address _asset = asset; for (uint256 i; i < tokenIds.length; i++) { IERC721(_asset).safeTransferFrom(address(this), owner(), tokenIds[i]); } } }
* @notice Transfers all balance of ERC721 `asset` from `this` contract to `owner`/
function _returnAssets(uint256[] memory tokenIds) internal virtual override { address _asset = asset; for (uint256 i; i < tokenIds.length; i++) { IERC721(_asset).safeTransferFrom(address(this), owner(), tokenIds[i]); } }
13,018,660
[ 1, 1429, 18881, 777, 11013, 434, 4232, 39, 27, 5340, 1375, 9406, 68, 628, 1375, 2211, 68, 6835, 358, 1375, 8443, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2463, 10726, 12, 11890, 5034, 8526, 3778, 1147, 2673, 13, 2713, 5024, 3849, 288, 203, 3639, 1758, 389, 9406, 273, 3310, 31, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 1147, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 467, 654, 39, 27, 5340, 24899, 9406, 2934, 4626, 5912, 1265, 12, 2867, 12, 2211, 3631, 3410, 9334, 1147, 2673, 63, 77, 19226, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // 'SPEX' 'ShareProfitEx' // // Symbol : SPEX // Name : ShareProfitEx // Total supply: 200,000,000.000000000000000000 // Decimals : 18 // // // (c) BokkyPooBah / Bok Consulting Pty Ltd 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { 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 function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract SPEX is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function SPEX() public { symbol = "SPEX"; name = "ShareProfitEx"; decimals = 18; _totalSupply = 200000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract SPEX is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function SPEX() public { symbol = "SPEX"; name = "ShareProfitEx"; decimals = 18; _totalSupply = 200000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
331,008
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 392, 2172, 5499, 14467, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 1423, 60, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 348, 1423, 60, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 23810, 60, 14432, 203, 3639, 508, 273, 315, 9535, 626, 7216, 424, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 576, 12648, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 3410, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 5381, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 324, 26488, 63, 3576, 18, 2 ]
pragma solidity ^0.4.24; import "./AddrPublic.sol"; contract PermsMng is AddrPublic { // owner from entry contract address owner; // perm owner addresses address[] public governs; event GovernUpdated(uint id, address prevGovern, address newGovern); event PermUpdated(uint id, address prevPerm, address newPerm); modifier onlyOwner { require(msg.sender == owner, "Not the owner"); _; } constructor() public { owner = msg.sender; for (uint i = 0; i < perms.length; i++) { governs.push(owner); } } function setGovern(uint id, address newGovern) external onlyOwner { address prev = governs[id]; governs[id] = newGovern; emit GovernUpdated(id, prev, newGovern); } function setPerm(uint id, address newPerm) external onlyOwner { address prev = perms[id]; perms[id] = newPerm; emit PermUpdated(id, prev, newPerm); } }
owner from entry contract perm owner addresses
contract PermsMng is AddrPublic { address owner; address[] public governs; event GovernUpdated(uint id, address prevGovern, address newGovern); event PermUpdated(uint id, address prevPerm, address newPerm); modifier onlyOwner { require(msg.sender == owner, "Not the owner"); _; } constructor() public { owner = msg.sender; for (uint i = 0; i < perms.length; i++) { governs.push(owner); } } constructor() public { owner = msg.sender; for (uint i = 0; i < perms.length; i++) { governs.push(owner); } } function setGovern(uint id, address newGovern) external onlyOwner { address prev = governs[id]; governs[id] = newGovern; emit GovernUpdated(id, prev, newGovern); } function setPerm(uint id, address newPerm) external onlyOwner { address prev = perms[id]; perms[id] = newPerm; emit PermUpdated(id, prev, newPerm); } }
12,781,068
[ 1, 8443, 628, 1241, 6835, 4641, 3410, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 453, 5044, 49, 3368, 353, 10216, 4782, 288, 203, 565, 1758, 3410, 31, 203, 565, 1758, 8526, 1071, 314, 1643, 2387, 31, 203, 203, 565, 871, 611, 1643, 82, 7381, 12, 11890, 612, 16, 1758, 2807, 43, 1643, 82, 16, 1758, 394, 43, 1643, 82, 1769, 203, 203, 565, 871, 13813, 7381, 12, 11890, 612, 16, 1758, 2807, 9123, 16, 1758, 394, 9123, 1769, 203, 203, 565, 9606, 1338, 5541, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 1248, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 13793, 18, 2469, 31, 277, 27245, 288, 203, 5411, 314, 1643, 2387, 18, 6206, 12, 8443, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 13793, 18, 2469, 31, 277, 27245, 288, 203, 5411, 314, 1643, 2387, 18, 6206, 12, 8443, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 26770, 1643, 82, 12, 11890, 612, 16, 1758, 394, 43, 1643, 82, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 1758, 2807, 273, 314, 1643, 2387, 63, 350, 15533, 203, 3639, 314, 1643, 2387, 63, 350, 65, 273, 394, 43, 1643, 82, 31, 203, 3639, 3626, 611, 1643, 82, 7381, 12, 350, 16, 2 ]
pragma solidity ^0.4.24; contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(_beneficiary, _weiAmount); * require(weiRaised.add(_weiAmount) <= cap); * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Withdraw tokens only after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } contract Oraclized is Ownable { address public oracle; constructor(address _oracle) public { oracle = _oracle; } /** * @dev Change oracle address * @param _oracle Oracle address */ function setOracle(address _oracle) public onlyOwner { oracle = _oracle; } /** * @dev Modifier to allow access only by oracle */ modifier onlyOracle() { require(msg.sender == oracle); _; } /** * @dev Modifier to allow access only by oracle or owner */ modifier onlyOwnerOrOracle() { require((msg.sender == oracle) || (msg.sender == owner)); _; } } contract KYCCrowdsale is Oraclized, PostDeliveryCrowdsale { using SafeMath for uint256; /** * @dev etherPriceInUsd Ether price in cents * @dev usdRaised Total USD raised while ICO in cents * @dev weiInvested Stores amount of wei invested by each user * @dev usdInvested Stores amount of USD invested by each user in cents */ uint256 public etherPriceInUsd; uint256 public usdRaised; mapping (address => uint256) public weiInvested; mapping (address => uint256) public usdInvested; /** * @dev KYCPassed Registry of users who passed KYC * @dev KYCRequired Registry of users who has to passed KYC */ mapping (address => bool) public KYCPassed; mapping (address => bool) public KYCRequired; /** * @dev KYCRequiredAmountInUsd Amount in cents invested starting from which user must pass KYC */ uint256 public KYCRequiredAmountInUsd; event EtherPriceUpdated(uint256 _cents); /** * @param _kycAmountInUsd Amount in cents invested starting from which user must pass KYC */ constructor(uint256 _kycAmountInUsd, uint256 _etherPrice) public { require(_etherPrice > 0); KYCRequiredAmountInUsd = _kycAmountInUsd; etherPriceInUsd = _etherPrice; } /** * @dev Update amount required to pass KYC * @param _cents Amount in cents invested starting from which user must pass KYC */ function setKYCRequiredAmount(uint256 _cents) external onlyOwnerOrOracle { require(_cents > 0); KYCRequiredAmountInUsd = _cents; } /** * @dev Set ether conversion rate * @param _cents Price of 1 ETH in cents */ function setEtherPrice(uint256 _cents) public onlyOwnerOrOracle { require(_cents > 0); etherPriceInUsd = _cents; emit EtherPriceUpdated(_cents); } /** * @dev Check if KYC is required for address * @param _address Address to check */ function isKYCRequired(address _address) external view returns(bool) { return KYCRequired[_address]; } /** * @dev Check if KYC is passed by address * @param _address Address to check */ function isKYCPassed(address _address) external view returns(bool) { return KYCPassed[_address]; } /** * @dev Check if KYC is not required or passed * @param _address Address to check */ function isKYCSatisfied(address _address) public view returns(bool) { return !KYCRequired[_address] || KYCPassed[_address]; } /** * @dev Returns wei invested by specific amount * @param _account Account you would like to get wei for */ function weiInvestedOf(address _account) external view returns (uint256) { return weiInvested[_account]; } /** * @dev Returns cents invested by specific amount * @param _account Account you would like to get cents for */ function usdInvestedOf(address _account) external view returns (uint256) { return usdInvested[_account]; } /** * @dev Update KYC status for set of addresses * @param _addresses Addresses to update * @param _completed Is KYC passed or not */ function updateKYCStatus(address[] _addresses, bool _completed) public onlyOwnerOrOracle { for (uint16 index = 0; index < _addresses.length; index++) { KYCPassed[_addresses[index]] = _completed; } } /** * @dev Override update purchasing state * - update sum of funds invested * - if total amount invested higher than KYC amount set KYC required to true */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { super._updatePurchasingState(_beneficiary, _weiAmount); uint256 usdAmount = _weiToUsd(_weiAmount); usdRaised = usdRaised.add(usdAmount); usdInvested[_beneficiary] = usdInvested[_beneficiary].add(usdAmount); weiInvested[_beneficiary] = weiInvested[_beneficiary].add(_weiAmount); if (usdInvested[_beneficiary] >= KYCRequiredAmountInUsd) { KYCRequired[_beneficiary] = true; } } /** * @dev Override token withdraw * - do not allow token withdraw in case KYC required but not passed */ function withdrawTokens() public { require(isKYCSatisfied(msg.sender)); super.withdrawTokens(); } /** * @dev Converts wei to cents * @param _wei Wei amount */ function _weiToUsd(uint256 _wei) internal view returns (uint256) { return _wei.mul(etherPriceInUsd).div(1e18); } /** * @dev Converts cents to wei * @param _cents Cents amount */ function _usdToWei(uint256 _cents) internal view returns (uint256) { return _cents.mul(1e18).div(etherPriceInUsd); } } contract KYCRefundableCrowdsale is KYCCrowdsale { using SafeMath for uint256; /** * @dev percentage multiplier to present percentage as decimals. 5 decimal by default * @dev weiOnFinalize ether balance which was on finalize & will be returned to users in case of failed crowdsale */ uint256 private percentage = 100 * 1000; uint256 private weiOnFinalize; /** * @dev goalReached specifies if crowdsale goal is reached * @dev isFinalized is crowdsale finished * @dev tokensWithdrawn total amount of tokens already withdrawn */ bool public goalReached = false; bool public isFinalized = false; uint256 public tokensWithdrawn; event Refund(address indexed _account, uint256 _amountInvested, uint256 _amountRefunded); event Finalized(); event OwnerWithdraw(uint256 _amount); /** * @dev Set is goal reached or not * @param _success Is goal reached or not */ function setGoalReached(bool _success) external onlyOwner { require(!isFinalized); goalReached = _success; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached); uint256 refundPercentage = _refundPercentage(); uint256 amountInvested = weiInvested[msg.sender]; uint256 amountRefunded = amountInvested.mul(refundPercentage).div(percentage); weiInvested[msg.sender] = 0; usdInvested[msg.sender] = 0; msg.sender.transfer(amountRefunded); emit Refund(msg.sender, amountInvested, amountRefunded); } /** * @dev Must be called after crowdsale ends, to do some extra finalization works. */ function finalize() public onlyOwner { require(!isFinalized); // NOTE: We do this because we would like to allow withdrawals earlier than closing time in case of crowdsale success closingTime = block.timestamp; weiOnFinalize = address(this).balance; isFinalized = true; emit Finalized(); } /** * @dev Override. Withdraw tokens only after crowdsale ends. * Make sure crowdsale is successful & finalized */ function withdrawTokens() public { require(isFinalized); require(goalReached); tokensWithdrawn = tokensWithdrawn.add(balances[msg.sender]); super.withdrawTokens(); } /** * @dev Is called by owner to send funds to ICO wallet. * params _amount Amount to be sent. */ function ownerWithdraw(uint256 _amount) external onlyOwner { require(_amount > 0); wallet.transfer(_amount); emit OwnerWithdraw(_amount); } /** * @dev Override. Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { // NOTE: Do nothing here. Keep funds in contract by default } /** * @dev Calculates refund percentage in case some funds will be used by dev team on crowdsale needs */ function _refundPercentage() internal view returns (uint256) { return weiOnFinalize.mul(percentage).div(weiRaised); } } contract AerumCrowdsale is KYCRefundableCrowdsale { using SafeMath for uint256; /** * @dev minInvestmentInUsd Minimal investment allowed in cents */ uint256 public minInvestmentInUsd; /** * @dev tokensSold Amount of tokens sold by this time */ uint256 public tokensSold; /** * @dev pledgeTotal Total pledge collected from all investors * @dev pledgeClosingTime Time when pledge is closed & it's not possible to pledge more or use pledge more * @dev pledges Mapping of all pledges done by investors */ uint256 public pledgeTotal; uint256 public pledgeClosingTime; mapping (address => uint256) public pledges; /** * @dev whitelistedRate Rate which is used while whitelisted sale (XRM to ETH) * @dev publicRate Rate which is used white public crowdsale (XRM to ETH) */ uint256 public whitelistedRate; uint256 public publicRate; event AirDrop(address indexed _account, uint256 _amount); event MinInvestmentUpdated(uint256 _cents); event RateUpdated(uint256 _whitelistedRate, uint256 _publicRate); event Withdraw(address indexed _account, uint256 _amount); /** * @param _token ERC20 compatible token on which crowdsale is done * @param _wallet Address where all ETH funded will be sent after ICO finishes * @param _whitelistedRate Rate which is used while whitelisted sale * @param _publicRate Rate which is used white public crowdsale * @param _openingTime Crowdsale open time * @param _closingTime Crowdsale close time * @param _pledgeClosingTime Time when pledge is closed & no more active \\ * @param _kycAmountInUsd Amount on which KYC will be required in cents * @param _etherPriceInUsd ETH price in cents */ constructor( ERC20 _token, address _wallet, uint256 _whitelistedRate, uint256 _publicRate, uint256 _openingTime, uint256 _closingTime, uint256 _pledgeClosingTime, uint256 _kycAmountInUsd, uint256 _etherPriceInUsd) Oraclized(msg.sender) Crowdsale(_whitelistedRate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) KYCCrowdsale(_kycAmountInUsd, _etherPriceInUsd) KYCRefundableCrowdsale() public { require(_openingTime < _pledgeClosingTime && _pledgeClosingTime < _closingTime); pledgeClosingTime = _pledgeClosingTime; whitelistedRate = _whitelistedRate; publicRate = _publicRate; minInvestmentInUsd = 25 * 100; } /** * @dev Update minimal allowed investment */ function setMinInvestment(uint256 _cents) external onlyOwnerOrOracle { minInvestmentInUsd = _cents; emit MinInvestmentUpdated(_cents); } /** * @dev Update closing time * @param _closingTime Closing time */ function setClosingTime(uint256 _closingTime) external onlyOwner { require(_closingTime >= openingTime); closingTime = _closingTime; } /** * @dev Update pledge closing time * @param _pledgeClosingTime Pledge closing time */ function setPledgeClosingTime(uint256 _pledgeClosingTime) external onlyOwner { require(_pledgeClosingTime >= openingTime && _pledgeClosingTime <= closingTime); pledgeClosingTime = _pledgeClosingTime; } /** * @dev Update rates * @param _whitelistedRate Rate which is used while whitelisted sale (XRM to ETH) * @param _publicRate Rate which is used white public crowdsale (XRM to ETH) */ function setRate(uint256 _whitelistedRate, uint256 _publicRate) public onlyOwnerOrOracle { require(_whitelistedRate > 0); require(_publicRate > 0); whitelistedRate = _whitelistedRate; publicRate = _publicRate; emit RateUpdated(_whitelistedRate, _publicRate); } /** * @dev Update rates & ether price. Done to not make 2 requests from oracle. * @param _whitelistedRate Rate which is used while whitelisted sale * @param _publicRate Rate which is used white public crowdsale * @param _cents Price of 1 ETH in cents */ function setRateAndEtherPrice(uint256 _whitelistedRate, uint256 _publicRate, uint256 _cents) external onlyOwnerOrOracle { setRate(_whitelistedRate, _publicRate); setEtherPrice(_cents); } /** * @dev Send remaining tokens back * @param _to Address to send * @param _amount Amount to send */ function sendTokens(address _to, uint256 _amount) external onlyOwner { if (!isFinalized || goalReached) { // NOTE: if crowdsale not finished or successful we should keep at least tokens sold _ensureTokensAvailable(_amount); } token.transfer(_to, _amount); } /** * @dev Get balance fo tokens bought * @param _address Address of investor */ function balanceOf(address _address) external view returns (uint256) { return balances[_address]; } /** * @dev Check if all tokens were sold */ function capReached() public view returns (bool) { return tokensSold >= token.balanceOf(this); } /** * @dev Returns percentage of tokens sold */ function completionPercentage() external view returns (uint256) { uint256 balance = token.balanceOf(this); if (balance == 0) { return 0; } return tokensSold.mul(100).div(balance); } /** * @dev Returns remaining tokens based on stage */ function tokensRemaining() external view returns(uint256) { return token.balanceOf(this).sub(_tokensLocked()); } /** * @dev Override. Withdraw tokens only after crowdsale ends. * Adding withdraw event */ function withdrawTokens() public { uint256 amount = balances[msg.sender]; super.withdrawTokens(); emit Withdraw(msg.sender, amount); } /** * @dev Override crowdsale pre validate. Check: * - is amount invested larger than minimal * - there is enough tokens on balance of contract to proceed * - check if pledges amount are not more than total coins (in case of pledge period) */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(_totalInvestmentInUsd(_beneficiary, _weiAmount) >= minInvestmentInUsd); _ensureTokensAvailableExcludingPledge(_beneficiary, _getTokenAmount(_weiAmount)); } /** * @dev Returns total investment of beneficiary including current one in cents * @param _beneficiary Address to check * @param _weiAmount Current amount being invested in wei */ function _totalInvestmentInUsd(address _beneficiary, uint256 _weiAmount) internal view returns(uint256) { return usdInvested[_beneficiary].add(_weiToUsd(_weiAmount)); } /** * @dev Override process purchase * - additionally sum tokens sold */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { super._processPurchase(_beneficiary, _tokenAmount); tokensSold = tokensSold.add(_tokenAmount); if (pledgeOpen()) { // NOTE: In case of buying tokens inside pledge it doesn't matter how we decrease pledge as we change it anyway _decreasePledge(_beneficiary, _tokenAmount); } } /** * @dev Decrease pledge of account by specific token amount * @param _beneficiary Account to increase pledge * @param _tokenAmount Amount of tokens to decrease pledge */ function _decreasePledge(address _beneficiary, uint256 _tokenAmount) internal { if (pledgeOf(_beneficiary) <= _tokenAmount) { pledgeTotal = pledgeTotal.sub(pledgeOf(_beneficiary)); pledges[_beneficiary] = 0; } else { pledgeTotal = pledgeTotal.sub(_tokenAmount); pledges[_beneficiary] = pledges[_beneficiary].sub(_tokenAmount); } } /** * @dev Override to use whitelisted or public crowdsale rates */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return _weiAmount.mul(currentRate); } /** * @dev Returns current XRM to ETH rate based on stage */ function getCurrentRate() public view returns (uint256) { if (pledgeOpen()) { return whitelistedRate; } return publicRate; } /** * @dev Check if pledge period is still open */ function pledgeOpen() public view returns (bool) { return (openingTime <= block.timestamp) && (block.timestamp <= pledgeClosingTime); } /** * @dev Returns amount of pledge for account */ function pledgeOf(address _address) public view returns (uint256) { return pledges[_address]; } /** * @dev Check if all tokens were pledged */ function pledgeCapReached() public view returns (bool) { return pledgeTotal.add(tokensSold) >= token.balanceOf(this); } /** * @dev Returns percentage of tokens pledged */ function pledgeCompletionPercentage() external view returns (uint256) { uint256 balance = token.balanceOf(this); if (balance == 0) { return 0; } return pledgeTotal.add(tokensSold).mul(100).div(balance); } /** * @dev Pledges * @param _addresses list of addresses * @param _tokens List of tokens to drop */ function pledge(address[] _addresses, uint256[] _tokens) external onlyOwnerOrOracle { require(_addresses.length == _tokens.length); _ensureTokensListAvailable(_tokens); for (uint16 index = 0; index < _addresses.length; index++) { pledgeTotal = pledgeTotal.sub(pledges[_addresses[index]]).add(_tokens[index]); pledges[_addresses[index]] = _tokens[index]; } } /** * @dev Air drops tokens to users * @param _addresses list of addresses * @param _tokens List of tokens to drop */ function airDropTokens(address[] _addresses, uint256[] _tokens) external onlyOwnerOrOracle { require(_addresses.length == _tokens.length); _ensureTokensListAvailable(_tokens); for (uint16 index = 0; index < _addresses.length; index++) { tokensSold = tokensSold.add(_tokens[index]); balances[_addresses[index]] = balances[_addresses[index]].add(_tokens[index]); emit AirDrop(_addresses[index], _tokens[index]); } } /** * @dev Ensure token list total is available * @param _tokens list of tokens amount */ function _ensureTokensListAvailable(uint256[] _tokens) internal { uint256 total; for (uint16 index = 0; index < _tokens.length; index++) { total = total.add(_tokens[index]); } _ensureTokensAvailable(total); } /** * @dev Ensure amount of tokens you would like to buy or pledge is available * @param _tokens Amount of tokens to buy or pledge */ function _ensureTokensAvailable(uint256 _tokens) internal view { require(_tokens.add(_tokensLocked()) <= token.balanceOf(this)); } /** * @dev Ensure amount of tokens you would like to buy or pledge is available excluding pledged for account * @param _account Account which is checked for pledge * @param _tokens Amount of tokens to buy or pledge */ function _ensureTokensAvailableExcludingPledge(address _account, uint256 _tokens) internal view { require(_tokens.add(_tokensLockedExcludingPledge(_account)) <= token.balanceOf(this)); } /** * @dev Returns locked or sold tokens based on stage */ function _tokensLocked() internal view returns(uint256) { uint256 locked = tokensSold.sub(tokensWithdrawn); if (pledgeOpen()) { locked = locked.add(pledgeTotal); } return locked; } /** * @dev Returns locked or sold tokens based on stage excluding pledged for account * @param _account Account which is checked for pledge */ function _tokensLockedExcludingPledge(address _account) internal view returns(uint256) { uint256 locked = _tokensLocked(); if (pledgeOpen()) { locked = locked.sub(pledgeOf(_account)); } return locked; } }
* @dev Returns locked or sold tokens based on stage excluding pledged for account @param _account Account which is checked for pledge/
function _tokensLockedExcludingPledge(address _account) internal view returns(uint256) { uint256 locked = _tokensLocked(); if (pledgeOpen()) { locked = locked.sub(pledgeOf(_account)); } return locked; }
889,626
[ 1, 1356, 8586, 578, 272, 1673, 2430, 2511, 603, 6009, 19560, 293, 1259, 2423, 364, 2236, 225, 389, 4631, 6590, 1492, 353, 5950, 364, 293, 19998, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 7860, 8966, 424, 18596, 52, 19998, 12, 2867, 389, 4631, 13, 2713, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 8586, 273, 389, 7860, 8966, 5621, 203, 203, 3639, 309, 261, 84, 19998, 3678, 10756, 288, 203, 5411, 8586, 273, 8586, 18, 1717, 12, 84, 19998, 951, 24899, 4631, 10019, 203, 3639, 289, 203, 203, 3639, 327, 8586, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; contract Gen { // MAPPINGS // mapping(string => uint) internal charsMap; // maps characters to numbers for easier access in 'generateWord()' function mapping(uint => uint) internal tokenIdToSeed; // initial seed for each tokenId minted mapping(uint => uint[8]) internal tokenIdToShuffleShift; // tokenId => array of inexes for words to be shifted as a result of shuffling mapping(uint => uint) internal shuffleCount; // tokenId => number of shuffles tokenId has had mapping(address => bool) internal hasClaimed; // keeps track of addresses that have claimed a mint /** * @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); } // VARIABLES // uint16[297] ps = [ 1000, 1889, 2889, 3556, 5223, 6223, 7334, 8778, 9334, 9556, 10000, 381, 952, 1428, 1809, 2761, 4856, 6094, 7523, 9523, 9809, 10000, 198, 792, 1584, 2079, 2574, 3267, 3366, 5643, 7029, 9900, 10000, 714, 1071, 1607, 2232, 2945, 4285, 5178, 6516, 7856, 9195, 10000, 385, 1348, 3467, 5201, 6163, 7127, 9824, 9920, 9939, 9958, 10000, 135, 405, 1081, 1216, 1892, 2703, 4325, 5541, 7568, 9730, 10000, 2443, 2932, 3421, 3910, 4561, 5212, 6677, 8470, 9936, 9985, 10000, 1239, 1770, 2655, 4071, 5310, 6726, 7257, 9912, 9947, 9982, 10000, 268, 281, 294, 328, 1668, 4751, 7432, 9979, 9986, 9993, 10000, 291, 679, 1164, 1649, 2329, 3106, 3689, 4951, 6504, 9708, 10000, 353, 706, 1923, 3510, 5097, 7672, 8818, 9964, 9982, 9991, 10000, 755, 1227, 1416, 1605, 1888, 2077, 2171, 3114, 9246, 9812, 10000, 695, 721, 747, 834, 851, 3023, 5195, 6846, 9974, 9991, 10000, 103, 308, 513, 821, 1437, 2566, 3901, 7289, 9958, 9979, 10000, 294, 588, 735, 750, 1337, 2071, 2805, 4127, 6183, 8239, 10000, 88, 1148, 2561, 2738, 3975, 4682, 4859, 5389, 7156, 9983, 10000, 325, 760, 1303, 1629, 1955, 3367, 4670, 6624, 8253, 9990, 10000, 4955, 9910, 9920, 9930, 9940, 9950, 9960, 9970, 9980, 9990, 10000, 214, 428, 641, 663, 1197, 1411, 1454, 2522, 3590, 4658, 10000, 196, 784, 2548, 3332, 4312, 5488, 7644, 9800, 9996, 9998, 10000, 475, 1424, 1661, 2848, 4272, 5933, 8544, 9256, 9968, 9992, 10000, 515, 618, 1133, 1442, 2267, 3298, 4947, 6493, 7730, 9483, 10000, 202, 1412, 3025, 5444, 7662, 9880, 9920, 9940, 9960, 9980, 10000, 23, 252, 480, 2657, 2886, 4719, 7354, 9645, 9874, 9885, 10000, 433, 866, 1732, 3464, 5195, 8659, 9525, 9698, 9871, 9958, 10000, 601, 901, 1502, 2103, 3605, 4806, 6007, 9010, 9310, 9400, 10000, 204, 511, 613, 714, 1737, 3782, 9917, 9968, 9978, 9988, 10000]; string[] nextChars = [ "fbrwsaltpzj", "gmldslrtnkb", "blriiluoaey", "rliktauhooe", "ruaoiiegfws", "mfteladsnrg", "luaarreioyw", "luiraohezgy", "urryoiaejlw", "gredlocstnb", "iieaaouuytf", "aollarsieut", "ussdyoaielf", "smmupioaeyn", "aauyiosetgd", "zolwtmfurny", "tupiilaores", "uuaeiosrfyw", "nudytslaioe", "puhaoietwyq", "usraieohhty", "ebgzplsntrm", "uoaieeyvxrl", "snnoheaiuyr", "oaueeityxth", "lmaiseeouvx", "uyooiaelzrl"]; /** * @dev Maps characters in 'chars' to numbers for easier comparison in 'generateWord()' function */ function mapChars() internal { string[27] memory chars = [" ", "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; for (uint i=0; i<27; i++) { charsMap[chars[i]] = i; } } /** * @dev Returns length of a string '_string'. */ function stringLength(string memory _string) internal pure returns(uint) { return bytes(_string).length; } /** * @dev Gets character from 'nextChars'. */ function getChar(uint row, uint col) internal view returns(string memory) { bytes memory line = bytes(nextChars[row]); string memory temp = new string(1); bytes memory output = bytes(temp); output[0] = line[col]; return string(output); } /** * @dev Generates word length (1-16) using a distribution */ function determineWordLength(uint rand) internal pure returns(uint) { uint16[16] memory cumulativeDistribution = [2,99,761,1929,3175,4694,6291,7654,8744,9328,9678,9872,9938,9976,9991,10000]; uint i = 0; while (i <= 15) { if (rand <= cumulativeDistribution[i]) { break; } i++; } return i+1; // returns word length } /** * @dev Generates a random word of length 1-16, given a '_tokenId' and '_totalSeed' as a seed of randomness */ function generateWord(uint256 _tokenId, uint _totalSeed) internal view returns(string memory) { // change visibility require(_tokenId >= 1 && _tokenId <= 10000, "Invalid tokenId."); string memory word; string memory char; uint lengthRand = (uint(keccak256(abi.encodePacked(_tokenId, _totalSeed)))% 10000); // gets random number between 0 and 10,000 uint rand = (uint(keccak256(abi.encodePacked(_tokenId, lengthRand, _totalSeed)))% 10000) + 1; // gets random number between 1 and 10,000 // generates word for (uint n=1; n <= determineWordLength(lengthRand); n++) { // generates letter uint i = 0; while (i < 11) { // indexStart of ps[] to indexEnd if (rand <= ps[(charsMap[char]*11)+i]) { break; } i++; } char = getChar(charsMap[char], i); word = string(abi.encodePacked(word, char)); // appends letter to word rand = (uint(keccak256(abi.encodePacked(_tokenId, rand, word, n, _totalSeed)))% 10000) + 1; // gets new random number between 1 and 10,000 } return word; } }
indexStart of ps[] to indexEnd
while (i < 11) {
2,527,391
[ 1, 1615, 1685, 434, 4250, 8526, 358, 770, 1638, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 1323, 261, 77, 411, 4648, 13, 288, 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 ]
contract ParallelGambling { //--------parameters uint[3] private deposit; uint private feesThousandth = 10; //1% of fees ! uint private time_max = 6 * 60 * 60; //6 hours in seconds, time to wait before you can cancel the round uint private fees = 0; //percentage of attribution of differents prizes uint private first_prize = 170; //Big winner gets 160 % uint private second_prize = 130; //Little winner gets 140 % uint private third_prize = 0; //looser gets nothing ! //--Contract ledger for the 3 "play zones" uint[3] private Balance; uint[3] private id; uint[3] private cursor; uint[3] private nb_player ; uint[3] private last_time ; // -- random uniformers - uint256 private toss1; uint256 private toss2; address private admin; //Constructor - executed on creation only function ParallelGambling() { admin = msg.sender; uint i; //*****initiate everything properly**** for(i=0;i<3;i++){ Balance[i]=0; last_time[i] = block.timestamp; nb_player[i]=0; id[i]=0; cursor[i]=0; } deposit[0]= 100 finney; // ZONE 1 deposit[1]= 1 ether; // ZONE 2 deposit[2]= 5 ether; // ZONE 3 } modifier onlyowner {if (msg.sender == admin) _ } struct Player { //for each entry address addr; uint payout; //this section is filled when payout are done ! bool paid; } Player[][3] private players; struct GamblerStats { //for each address, to keep a record uint bets; uint deposits; uint paid; } mapping(address => GamblerStats) private gamblers; function() { init(); } function init() private { //------ Verifications to select play zone----- uint256 actual_deposit = msg.value; uint zone_selected; if (actual_deposit < deposit[0]) { //not enough for any zones ! msg.sender.send(actual_deposit); return; } if(actual_deposit >= deposit[0] && actual_deposit < deposit[1]){ // GAME ZONE 1 if( actual_deposit-deposit[0] >0){ msg.sender.send(actual_deposit-deposit[0]); } actual_deposit=deposit[0]; zone_selected=0; } if(actual_deposit >= deposit[1] && actual_deposit < deposit[2]){ // GAME ZONE 2 if( actual_deposit-deposit[1] >0){ msg.sender.send(actual_deposit-deposit[1]); } actual_deposit=deposit[1]; zone_selected=1; } if(actual_deposit >= deposit[2]){ // GAME ZONE 3 if( actual_deposit-deposit[2] >0){ msg.sender.send(actual_deposit-deposit[2]); } actual_deposit=deposit[2]; zone_selected=2; } //----update balances and ledger according to the playing zone selected--- fees += (actual_deposit * feesThousandth) / 1000; // collect 1% fee Balance[zone_selected] += (actual_deposit * (1000 - feesThousandth )) / 1000; //update balance last_time[zone_selected] = block.timestamp; players[zone_selected].length++; players[zone_selected][cursor[zone_selected]]=(Player(msg.sender, 0 , false)); cursor[zone_selected]++; nb_player[zone_selected]++; //update stats gamblers[msg.sender].bets++; gamblers[msg.sender].deposits += actual_deposit; //random if(nb_player[zone_selected]%2 ==0) toss1 = uint256(sha3(msg.gas)) + uint256(sha3(block.timestamp)); else toss2 = uint256(sha3(tx.gasprice+block.difficulty)); //-check if end of the round if(nb_player[zone_selected] == 3){ //end of a round EndRound(zone_selected); } } function EndRound(uint zone) private{ //randomness is created here from previous toss uint256 toss = toss1+toss2+msg.value; //send a value higher than the required deposit to create more randomness if you are the third player (ending round). //indices of players uint i_big_winner; uint i_small_winner; uint i_looser; if( toss % 3 == 0 ){ i_big_winner=id[zone]; i_small_winner=id[zone]+1; i_looser =id[zone]+2; } else if( toss % 3 == 1){ i_big_winner=id[zone]+2; i_small_winner=id[zone]; i_looser =id[zone]+1; } else{ i_big_winner=id[zone]+1; i_small_winner=id[zone]+2; i_looser =id[zone]; } uint256 effective_bet = (deposit[zone] * (1000 - feesThousandth )) / 1000; players[zone][i_big_winner].addr.send(effective_bet*first_prize/100); //big win players[zone][i_small_winner].addr.send(effective_bet*second_prize/100); //small win if(third_prize > 0){ players[zone][i_small_winner].addr.send(effective_bet*third_prize/100); //looser } //update zone information players[zone][i_big_winner].payout=effective_bet*first_prize/100; players[zone][i_small_winner].payout=effective_bet*second_prize/100; players[zone][i_looser].payout=effective_bet*third_prize/100; players[zone][id[zone]].paid=true; players[zone][id[zone]+1].paid=true; players[zone][id[zone]+2].paid=true; //update gamblers ledger gamblers[players[zone][i_big_winner].addr].paid += players[zone][i_big_winner].payout; gamblers[players[zone][i_small_winner].addr].paid += players[zone][i_small_winner].payout; gamblers[players[zone][i_looser].addr].paid += players[zone][i_looser].payout; Balance[zone]=0; nb_player[zone]=0; id[zone] += 3; } function CancelRoundAndRefundAll(uint zone) { //refund every participants in a zone, anyone can call this ! if(zone<0 && zone>3) throw; if(nb_player[zone]==0) return; uint256 pay=(deposit[zone] * (1000 - feesThousandth )) / 1000; if (last_time[zone] + time_max < block.timestamp) { for(uint i=id[zone]; i<(id[zone]+nb_player[zone]); i++){ players[zone][i].addr.send(pay); players[zone][i].paid=true; players[zone][i].payout=pay; gamblers[players[zone][i].addr].bets--; gamblers[players[zone][i].addr].deposits -= pay; } id[zone] += nb_player[zone]; nb_player[zone]=0; Balance[zone]=0; //remove informations from stats - cancelling = removing } } //------------ Contract informations ----------------------------------- function LookAtBalance() constant returns(uint BalanceOfZone1,uint BalanceOfZone2,uint BalanceOfZone3, string info) { BalanceOfZone1 = Balance[0] / 1 finney; BalanceOfZone2 = Balance[1] / 1 finney; BalanceOfZone3 = Balance[2] / 1 finney; info ='Balances of all play zones in finney'; } function PlayerInfoPerZone(uint id, uint zone) constant returns(address Address, uint Payout, bool UserPaid, string info) { if(zone<0 && zone>3) throw; if (id <= players[zone].length) { Address = players[zone][id].addr; Payout = (players[zone][id].payout) / 1 finney; UserPaid= players[zone][id].paid; } info = 'Select zone between 0 and 2, then use the id to look trough this zone'; } function LookAtLastTimePerZone(uint zone) constant returns(uint LastTimeForSelectedZone,uint TimeToWaitEnablingRefund, string info) { if(zone<0 && zone>3) throw; LastTimeForSelectedZone = last_time[zone]; TimeToWaitEnablingRefund = time_max; info ='Timestamps, use this to know when you can cancel a round to get back funds, TimeToWait in seconds !'; } function LookAtCollectedFees() constant returns(uint Fees, string info) { Fees = fees / 1 finney; info = 'Fees collected, in finney.'; } function LookAtDepositsToPlay() constant returns(uint InZone1,uint InZone2,uint InZone3, string info) { InZone1 = deposit[0] / 1 finney; InZone2 = deposit[1] / 1 finney; InZone3 = deposit[2] / 1 finney; info = 'Deposit for each zones, in finney. Surpus are always refunded.'; } function LookAtPrizes() constant returns(uint FirstPrize,uint SecondPrize,uint LooserPrize, string info) { FirstPrize=first_prize; SecondPrize=second_prize; LooserPrize=third_prize; info = 'Prizes in percent of the deposit'; } function GamblerPerAddress(address addr) constant returns(uint Bets, uint Deposited, uint PaidOut, string info) { Bets = gamblers[addr].bets; Deposited = gamblers[addr].deposits / 1 finney; PaidOut = gamblers[addr].paid / 1 finney; info ='Bets is the number of time you participated, no matter the zone.'; } function LookAtNumberOfPlayers() constant returns(uint InZone1,uint InZone2,uint InZone3, string info) { InZone1 = nb_player[0]; InZone2 = nb_player[1]; InZone3 = nb_player[2]; info = 'Players in a round, in each zones.'; } //----------- Contract management functions ------------------------- function ChangeOwnership(address _owner) onlyowner { admin = _owner; } function ModifyFeeFraction(uint new_fee) onlyowner { if( new_fee>=0 && new_fee<=20 ){ //admin can only set the fee percentage between 0 and 2%, initially 1% feesThousandth = new_fee; } } //function to modify settings, only if no player in a round ! function ModifySettings(uint new_time_max, uint new_first_prize, uint new_second_prize, uint new_third_prize, uint deposit_1,uint deposit_2,uint deposit_3) onlyowner { if(nb_player[0]!=0 || nb_player[1]!=0 || nb_player[2]!=0 ) throw; //can only modify if nobody plays ! if(new_time_max>=(1 * 60 * 60) && new_time_max<=(24 * 60 * 60) ) time_max=new_time_max; if((new_first_prize+new_second_prize+new_third_prize)==300){ //the total must be distributed in a correct way if(new_first_prize>=130 && new_first_prize<=190){ first_prize=new_first_prize; if(new_second_prize>100 && new_second_prize<=130){ second_prize=new_second_prize; if(new_third_prize>=0 && new_third_prize<=50) third_prize=new_third_prize; } } } if(deposit_1>=(1 finney) && deposit_1<(1 ether)) deposit[0]=deposit_1; if(deposit_2>=(1 ether) && deposit_2<(5 ether)) deposit[1]=deposit_2; if(deposit_3>=(5 ether) && deposit_3<=(20 ether)) deposit[2]=deposit_3; } function CollectAllFees() onlyowner { //it just send fees, that's all folks ! if (fees == 0) throw; admin.send(fees); fees = this.balance -Balance[0]-Balance[1]-Balance[2]; //just in case there is lost ethers. } }
function to modify settings, only if no player in a round !
uint deposit_1,uint deposit_2,uint deposit_3) onlyowner { if(new_time_max>=(1 * 60 * 60) && new_time_max<=(24 * 60 * 60) ) time_max=new_time_max; function ModifySettings(uint new_time_max, uint new_first_prize, uint new_second_prize, uint new_third_prize, if(new_first_prize>=130 && new_first_prize<=190){ first_prize=new_first_prize; if(new_second_prize>100 && new_second_prize<=130){ second_prize=new_second_prize; if(new_third_prize>=0 && new_third_prize<=50) third_prize=new_third_prize; } } function ModifySettings(uint new_time_max, uint new_first_prize, uint new_second_prize, uint new_third_prize, if(new_first_prize>=130 && new_first_prize<=190){ first_prize=new_first_prize; if(new_second_prize>100 && new_second_prize<=130){ second_prize=new_second_prize; if(new_third_prize>=0 && new_third_prize<=50) third_prize=new_third_prize; } } }
1,753,295
[ 1, 915, 358, 5612, 1947, 16, 1338, 309, 1158, 7291, 316, 279, 3643, 401, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 18701, 2254, 443, 1724, 67, 21, 16, 11890, 443, 1724, 67, 22, 16, 11890, 443, 1724, 67, 23, 13, 1338, 8443, 288, 203, 540, 203, 3639, 309, 12, 2704, 67, 957, 67, 1896, 34, 28657, 21, 380, 4752, 380, 4752, 13, 597, 394, 67, 957, 67, 1896, 32, 28657, 3247, 380, 4752, 380, 4752, 13, 262, 813, 67, 1896, 33, 2704, 67, 957, 67, 1896, 31, 203, 1082, 203, 565, 445, 9518, 2628, 12, 11890, 394, 67, 957, 67, 1896, 16, 2254, 394, 67, 3645, 67, 683, 554, 16, 2254, 394, 67, 8538, 67, 683, 554, 16, 2254, 394, 67, 451, 6909, 67, 683, 554, 16, 203, 1082, 202, 430, 12, 2704, 67, 3645, 67, 683, 554, 34, 33, 24417, 597, 394, 67, 3645, 67, 683, 554, 32, 33, 30454, 15329, 9506, 203, 9506, 202, 3645, 67, 683, 554, 33, 2704, 67, 3645, 67, 683, 554, 31, 203, 9506, 202, 430, 12, 2704, 67, 8538, 67, 683, 554, 34, 6625, 597, 394, 67, 8538, 67, 683, 554, 32, 33, 24417, 15329, 203, 6862, 202, 8538, 67, 683, 554, 33, 2704, 67, 8538, 67, 683, 554, 31, 203, 6862, 202, 430, 12, 2704, 67, 451, 6909, 67, 683, 554, 34, 33, 20, 597, 394, 67, 451, 6909, 67, 683, 554, 32, 33, 3361, 13, 12126, 67, 683, 554, 33, 2704, 67, 451, 6909, 67, 683, 554, 31, 203, 9506, 202, 97, 203, 1082, 202, 97, 203, 565, 445, 9518, 2628, 12, 11890, 394, 67, 957, 67, 1896, 16, 2254, 394, 67, 3645, 67, 683, 554, 2 ]
./partial_match/1/0x16e30b1f53E8E57c471dB5D449B4E742f04e1e94/sources/TreasureHunt.sol
solhint-disable-line
payable(owner()).call{value: address(this).balance}("");
3,884,822
[ 1, 18281, 11317, 17, 8394, 17, 1369, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8843, 429, 12, 8443, 1435, 2934, 1991, 95, 1132, 30, 1758, 12, 2211, 2934, 12296, 97, 2932, 8863, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-10-16 */ /* `` .:;:` ` ` ##### ## / ## ### /##### /## #/ /#### ### // / / ### ## / ### ## / / / ### ## /## ## / / ### ## / ## ## ## ## ## /## ### /### /## ## /## /### / ## ### /### /### /## ## /### ## ## ## / ### ###/ #### / / ### ## / ### / #### / / ## ###/ #### / / ### / / ### ## / #### / ## ## ## / ### ## ###/ / ### ##/ / ## ###/ / ## ## ###/ / ###/ / ### ## ## ###/ ## ## ## ## ### ## ## ### ## / s #### / ## ## ## ## ## ## ### ## #### ## ## ## ######## ## ######## ## / i ### /######## ## ## ## ## ######## ## ### # ## ## ####### ## ####### ## ## n ### / ## ## ## ## ## ####### ## ### / / ## ## ## ###### g ### # ## ## ## ## ## ## ## ### /###/ / #### / ## #### / ## ### l /### ## /#### ## ## ## ## ## #### / ## /### ## / ########/ ######/ ### ######/ ## ### / e / #### / / #### ## / ### ### ######## ######/ ### / / #### / / #### ##### ### ##### ## ##/ q ###/ / ## #/ ### ### ### ### ##### ##/ ###/ # u # ### ## o ## #### ### t /###### /# e / ###/ */ // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0-rc.0/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0-rc.0/contracts/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0-rc.0/contracts/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 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 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 6. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 6; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0-rc.0/contracts/token/ERC20/extensions/ERC20Burnable.sol pragma solidity ^0.8.0; /** * @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 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } } // File: contract/DereksAngels.sol pragma solidity ^0.8.0; /** * @dev {ERC20} token, including: * * - Preminted initial supply * - Ability for holders to burn (destroy) their tokens * - No access control mechanism (for minting/pausing) and hence no governance * * This contract uses {ERC20Burnable} to include burn capabilities - head to * its documentation for details. * * _Available since v3.4._ */ contract DereksAngels is ERC20Burnable { address public dao_admin; /** * @dev Mints `initialSupply` amount of token and transfers them to `owner`. * * See {ERC20-constructor}. */ constructor( string memory name, string memory symbol, uint256 initialSupply, address owner ) ERC20(name, symbol) { dao_admin = owner; _mint(dao_admin, initialSupply); } // Added to support recovering any token sent to this address to the dao_admin address function recoverERC20(address tokenAddress, uint256 tokenAmount) external{ IERC20(tokenAddress).transfer(dao_admin, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event Recovered(address token, uint256 amount); }
@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; } }
6,801,966
[ 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, 1377, 468, 1970, 7541, 4766, 282, 342, 27573, 7541, 4766, 282, 11849, 1171, 203, 19, 377, 342, 225, 342, 282, 11849, 1171, 9079, 7541, 27573, 342, 1189, 19694, 7541, 7734, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import "./Ownable.sol"; contract TaxReserve is Ownable { event Remitted(uint256 indexed _ref, uint256[] _ids); event Refunded(uint256 indexed _id, address indexed _from, address indexed _to, uint256 _principle, uint256 _tax); struct Transaction { uint id; address from; address to; uint256 principle; uint256 tax; uint256 blockNumber; bool expired; } uint256 public transactionCount = 0; mapping (uint256 => Transaction) public transactions; constructor(address _owner) public { require(address(owner) != 0x0); owner = _owner; //grantAccess(msg.sender); } /* Remit principle payment to payee and keep tax on reserve contract example: "asdf", ["0xca35b7d915458ef540ade6068dfe2f44e8fa733c"], ["1000000000000000000"], ["1000000000000000000"] */ function remit(uint256 ref, address[] _to, uint256[] _principle, uint256[] _tax) external payable { require(msg.value > 0 && _to.length > 0); require(_to.length == _principle.length && _to.length == _tax.length); uint256 total = 0; uint256[] memory txids = new uint256[](_to.length); for (uint256 i = 0; i < txids.length; i++) { address(_to[i]).transfer(_principle[i]); total += _principle[i] + _tax[i]; uint256 id = transactionCount = transactionCount + 1; Transaction storage trx = transactions[id]; trx.id = id; trx.from = msg.sender; trx.to = _to[i]; trx.principle = _principle[i]; trx.tax = _tax[i]; trx.blockNumber = block.number; trx.expired = false; txids[i] = id; } require(msg.value == total); emit Remitted(ref, txids); } function refundImpl(uint256 _id, uint256 _amount, uint256 _tax) private { Transaction memory trx = transactions[_id]; require(!trx.expired); // can only refund non-expired txs require(trx.principle >= _amount); // ensure not trying to refund more than a tx has. require(trx.tax >= _tax); // ensure not trying to refund more than a tx has. require(trx.to == msg.sender); // ensure refund is being sent by merchant who originally recieved the funds. // send payments. principle payment needs to succeed for tax payment to be paid. trx.from.transfer(_amount); trx.from.transfer(_tax); // update transaction with info so tax can't be stolen on future refunds against same tx. transactions[_id].principle = transactions[_id].principle - _amount; transactions[_id].tax = transactions[_id].tax - _tax; emit Refunded(trx.id, msg.sender, trx.from, _amount, _tax); } /* Refund principle and tax to original payor. example: ["1"], ["1000000000000000000"], ["1000000000000000000"] */ function refund(uint256[] _ids, uint256[] _amounts, uint256[] _taxs) external payable { require(msg.value > 0); // Make sure an actual refund is being given. require(_ids.length == _amounts.length); for (uint256 i = 0; i < _ids.length; i++) { refundImpl(_ids[i], _amounts[i], _taxs[i]); } } /* Expires all transactions 'before' a given block number. */ function expire(uint256 _beforeBlockNumber) external onlyOwner { require(_beforeBlockNumber < block.number); for (uint i = 0; i < transactionCount; i++) { if (transactions[i].blockNumber < _beforeBlockNumber) { transactions[i].expired = true; } } } /* Transfers given amount to sepcified address. */ function withdrawal(address _to, uint256 _amount) external onlyOwner { _to.transfer(_amount); } /* Retire contract so that it's not callable any longer. */ function retire() external onlyOwner { require(address(this).balance == 0); selfdestruct(msg.sender); } }
grantAccess(msg.sender);
constructor(address _owner) public { require(address(owner) != 0x0); owner = _owner; } example: "asdf", ["0xca35b7d915458ef540ade6068dfe2f44e8fa733c"], ["1000000000000000000"], ["1000000000000000000"]
2,527,637
[ 1, 16243, 1862, 12, 3576, 18, 15330, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 12, 2867, 389, 8443, 13, 1071, 288, 203, 3639, 2583, 12, 2867, 12, 8443, 13, 480, 374, 92, 20, 1769, 203, 3639, 3410, 273, 389, 8443, 31, 203, 565, 289, 203, 203, 540, 203, 3639, 3454, 30, 315, 345, 2180, 3113, 8247, 20, 92, 5353, 4763, 70, 27, 72, 29, 3600, 7950, 28, 10241, 6564, 20, 2486, 4848, 9470, 2180, 73, 22, 74, 6334, 73, 28, 507, 27, 3707, 71, 6, 6487, 8247, 21, 12648, 2787, 9449, 6, 6487, 8247, 21, 12648, 2787, 9449, 11929, 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 ]
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; import "./RegenesisMultisig.sol"; import "./AdditionalZkSync.sol"; /// @title zkSync main contract /// @author Matter Labs contract ZkSync is UpgradeableMaster, Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; bytes32 private constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /// @notice Data needed to process onchain operation from block public data. /// @notice Onchain operations is operations that need some processing on L1: Deposits, Withdrawals, ChangePubKey. /// @param ethWitness Some external data that can be needed for operation processing /// @param publicDataOffset Byte offset in public data for onchain operation struct OnchainOperationData { bytes ethWitness; uint32 publicDataOffset; } /// @notice Data needed to commit new block struct CommitBlockInfo { bytes32 newStateHash; bytes publicData; uint256 timestamp; OnchainOperationData[] onchainOperations; uint32 blockNumber; uint32 feeAccount; } /// @notice Data needed to execute committed and verified block /// @param commitmentsInSlot verified commitments in one slot /// @param commitmentIdx index such that commitmentsInSlot[commitmentIdx] is current block commitment struct ExecuteBlockInfo { StoredBlockInfo storedBlock; bytes[] pendingOnchainOpsPubdata; } /// @notice Recursive proof input data (individual commitments are constructed onchain) struct ProofInput { uint256[] recursiveInput; uint256[] proof; uint256[] commitments; uint8[] vkIndexes; uint256[16] subproofsLimbs; } // Upgrade functional /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external pure override returns (uint256) { return 0; } /// @notice Notification that upgrade notice period started /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeNoticePeriodStarted() external override { upgradeStartTimestamp = block.timestamp; } /// @notice Notification that upgrade preparation status is activated /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradePreparationStarted() external override { upgradePreparationActive = true; upgradePreparationActivationTime = block.timestamp; require(block.timestamp >= upgradeStartTimestamp.add(approvedUpgradeNoticePeriod)); } /// @dev When upgrade is finished or canceled we must clean upgrade-related state. function clearUpgradeStatus() internal { upgradePreparationActive = false; upgradePreparationActivationTime = 0; approvedUpgradeNoticePeriod = UPGRADE_NOTICE_PERIOD; emit NoticePeriodChange(approvedUpgradeNoticePeriod); upgradeStartTimestamp = 0; for (uint256 i = 0; i < SECURITY_COUNCIL_MEMBERS_NUMBER; ++i) { securityCouncilApproves[i] = false; } numberOfApprovalsFromSecurityCouncil = 0; } /// @notice Notification that upgrade canceled /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeCanceled() external override { clearUpgradeStatus(); } /// @notice Notification that upgrade finishes /// @dev Can be external because Proxy contract intercepts illegal calls of this function function upgradeFinishes() external override { clearUpgradeStatus(); } /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external view override returns (bool) { return !exodusMode; } /// @notice zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// @dev _governanceAddress The address of Governance contract /// @dev _verifierAddress The address of Verifier contract /// @dev _genesisStateHash Genesis blocks (first block) state tree root hash function initialize(bytes calldata initializationParameters) external { initializeReentrancyGuard(); ( Governance _governanceAddress, Verifier _verifierAddress, AdditionalZkSync _additionalZkSync, bytes32 _genesisStateHash ) = abi.decode(initializationParameters, (Governance, Verifier, AdditionalZkSync, bytes32)); verifier = _verifierAddress; governance = _governanceAddress; additionalZkSync = _additionalZkSync; StoredBlockInfo memory storedBlockZero = StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0)); storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero); approvedUpgradeNoticePeriod = UPGRADE_NOTICE_PERIOD; emit NoticePeriodChange(approvedUpgradeNoticePeriod); } /// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters // solhint-disable-next-line no-empty-blocks function upgrade(bytes calldata upgradeParameters) external nonReentrant {} function cutUpgradeNoticePeriod() external { /// All functions delegated to additional contract should NOT be nonReentrant delegateAdditional(); } /// @notice Sends tokens /// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount /// @dev This function is used to allow tokens to spend zkSync contract balance up to amount that is requested /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @param _maxAmount Maximum possible amount of tokens to transfer to this account function _transferERC20( IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount ) external returns (uint128 withdrawnAmount) { require(msg.sender == address(this), "5"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed) uint256 balanceBefore = _token.balanceOf(address(this)); require(Utils.sendERC20(_token, _to, _amount), "6"); // wtg11 - ERC20 transfer fails uint256 balanceAfter = _token.balanceOf(address(this)); uint256 balanceDiff = balanceBefore.sub(balanceAfter); require(balanceDiff <= _maxAmount, "7"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount return SafeCast.toUint128(balanceDiff); } /// @notice Accrues users balances from deposit priority requests in Exodus mode /// @dev WARNING: Only for Exodus mode /// @dev Canceling may take several separate transactions to be completed /// @param _n number of requests to process function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external { /// All functions delegated to additional contract should NOT be nonReentrant delegateAdditional(); } /// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit /// @param _zkSyncAddress The receiver Layer 2 address function depositETH(address _zkSyncAddress) external payable { require(_zkSyncAddress != SPECIAL_ACCOUNT_ADDRESS, "P"); requireActive(); registerDeposit(0, SafeCast.toUint128(msg.value), _zkSyncAddress); } /// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit /// @param _token Token address /// @param _amount Token amount /// @param _zkSyncAddress Receiver Layer 2 address function depositERC20( IERC20 _token, uint104 _amount, address _zkSyncAddress ) external nonReentrant { require(_zkSyncAddress != SPECIAL_ACCOUNT_ADDRESS, "P"); requireActive(); // Get token id by its address uint16 tokenId = governance.validateTokenAddress(address(_token)); require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused uint256 balanceBefore = _token.balanceOf(address(this)); require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "c"); // token transfer failed deposit uint256 balanceAfter = _token.balanceOf(address(this)); uint128 depositAmount = SafeCast.toUint128(balanceAfter.sub(balanceBefore)); require(depositAmount <= MAX_DEPOSIT_AMOUNT, "C"); registerDeposit(tokenId, depositAmount, _zkSyncAddress); } /// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract /// @param _address Address of the tokens owner /// @param _token Address of token, zero address is used for ETH function getPendingBalance(address _address, address _token) public view returns (uint128) { uint16 tokenId = 0; if (_token != address(0)) { tokenId = governance.validateTokenAddress(_token); } return pendingBalances[packAddressAndTokenId(_address, tokenId)].balanceToWithdraw; } /// @notice Withdraws tokens from zkSync contract to the owner /// @param _owner Address of the tokens owner /// @param _token Address of tokens, zero address is used for ETH /// @param _amount Amount to withdraw to request. /// NOTE: We will call ERC20.transfer(.., _amount), but if according to internal logic of ERC20 token zkSync contract /// balance will be decreased by value more then _amount we will try to subtract this value from user pending balance function withdrawPendingBalance( address payable _owner, address _token, uint128 _amount ) external nonReentrant { if (_token == address(0)) { registerWithdrawal(0, _amount, _owner); (bool success, ) = _owner.call{value: _amount}(""); require(success, "d"); // ETH withdraw failed } else { uint16 tokenId = governance.validateTokenAddress(_token); bytes22 packedBalanceKey = packAddressAndTokenId(_owner, tokenId); uint128 balance = pendingBalances[packedBalanceKey].balanceToWithdraw; // We will allow withdrawals of `value` such that: // `value` <= user pending balance // `value` can be bigger then `_amount` requested if token takes fee from sender in addition to `_amount` requested uint128 withdrawnAmount = this._transferERC20(IERC20(_token), _owner, _amount, balance); registerWithdrawal(tokenId, withdrawnAmount, _owner); } } /// @notice Withdraws NFT from zkSync contract to the owner /// @param _tokenId Id of NFT token function withdrawPendingNFTBalance(uint32 _tokenId) external nonReentrant { Operations.WithdrawNFT memory op = pendingWithdrawnNFTs[_tokenId]; require(op.creatorAddress != address(0), "op"); // No NFT to withdraw NFTFactory _factory = governance.getNFTFactory(op.creatorAccountId, op.creatorAddress); _factory.mintNFTFromZkSync( op.creatorAddress, op.receiver, op.creatorAccountId, op.serialId, op.contentHash, op.tokenId ); // Save withdrawn nfts for future deposits withdrawnNFTs[op.tokenId] = address(_factory); emit WithdrawalNFT(op.tokenId); delete pendingWithdrawnNFTs[_tokenId]; } /// @notice Register full exit request - pack pubdata, add priority request /// @param _accountId Numerical id of the account /// @param _token Token address, 0 address for ether function requestFullExit(uint32 _accountId, address _token) public nonReentrant { requireActive(); require(_accountId <= MAX_ACCOUNT_ID, "e"); require(_accountId != SPECIAL_ACCOUNT_ID, "v"); // request full exit for nft storage account uint16 tokenId; if (_token == address(0)) { tokenId = 0; } else { tokenId = governance.validateTokenAddress(_token); } // Priority Queue request Operations.FullExit memory op = Operations.FullExit({ accountId: _accountId, owner: msg.sender, tokenId: tokenId, amount: 0, // unknown at this point nftCreatorAccountId: uint32(0), // unknown at this point nftCreatorAddress: address(0), // unknown at this point nftSerialId: uint32(0), // unknown at this point nftContentHash: bytes32(0) // unknown at this point }); bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.FullExit, pubData); // User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value // In this case operator should just overwrite this slot during confirming withdrawal bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); pendingBalances[packedBalanceKey].gasReserveValue = FILLED_GAS_RESERVE_VALUE; } /// @notice Register full exit nft request - pack pubdata, add priority request /// @param _accountId Numerical id of the account /// @param _tokenId NFT token id in zkSync network function requestFullExitNFT(uint32 _accountId, uint32 _tokenId) public nonReentrant { requireActive(); require(_accountId <= MAX_ACCOUNT_ID, "e"); require(_accountId != SPECIAL_ACCOUNT_ID, "v"); // request full exit nft for nft storage account require(MAX_FUNGIBLE_TOKEN_ID < _tokenId && _tokenId < SPECIAL_NFT_TOKEN_ID, "T"); // request full exit nft for invalid token id // Priority Queue request Operations.FullExit memory op = Operations.FullExit({ accountId: _accountId, owner: msg.sender, tokenId: _tokenId, amount: 0, // unknown at this point nftCreatorAccountId: uint32(0), // unknown at this point nftCreatorAddress: address(0), // unknown at this point nftSerialId: uint32(0), // unknown at this point nftContentHash: bytes32(0) // unknown at this point }); bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.FullExit, pubData); } /// @dev Process one block commit using previous block StoredBlockInfo, /// @dev returns new block StoredBlockInfo /// @dev NOTE: Does not change storage (except events, so we can't mark it view) function commitOneBlock(StoredBlockInfo memory _previousBlock, CommitBlockInfo memory _newBlock) internal view returns (StoredBlockInfo memory storedNewBlock) { require(_newBlock.blockNumber == _previousBlock.blockNumber + 1, "f"); // only commit next block // Check timestamp of the new block { require(_newBlock.timestamp >= _previousBlock.timestamp, "g"); // Block should be after previous block bool timestampNotTooSmall = block.timestamp.sub(COMMIT_TIMESTAMP_NOT_OLDER) <= _newBlock.timestamp; bool timestampNotTooBig = _newBlock.timestamp <= block.timestamp.add(COMMIT_TIMESTAMP_APPROXIMATION_DELTA); require(timestampNotTooSmall && timestampNotTooBig, "h"); // New block timestamp is not valid } // Check onchain operations (bytes32 pendingOnchainOpsHash, uint64 priorityReqCommitted, bytes memory onchainOpsOffsetCommitment) = collectOnchainOps(_newBlock); // Create block commitment for verification proof bytes32 commitment = createBlockCommitment(_previousBlock, _newBlock, onchainOpsOffsetCommitment); return StoredBlockInfo( _newBlock.blockNumber, priorityReqCommitted, pendingOnchainOpsHash, _newBlock.timestamp, _newBlock.newStateHash, commitment ); } /// @notice Commit block /// @notice 1. Checks onchain operations, timestamp. /// @notice 2. Store block commitments function commitBlocks(StoredBlockInfo memory _lastCommittedBlockData, CommitBlockInfo[] memory _newBlocksData) external nonReentrant { requireActive(); governance.requireActiveValidator(msg.sender); // Check that we commit blocks after last committed block require(storedBlockHashes[totalBlocksCommitted] == hashStoredBlockInfo(_lastCommittedBlockData), "i"); // incorrect previous block data for (uint32 i = 0; i < _newBlocksData.length; ++i) { _lastCommittedBlockData = commitOneBlock(_lastCommittedBlockData, _newBlocksData[i]); totalCommittedPriorityRequests += _lastCommittedBlockData.priorityOperations; storedBlockHashes[_lastCommittedBlockData.blockNumber] = hashStoredBlockInfo(_lastCommittedBlockData); emit BlockCommit(_lastCommittedBlockData.blockNumber); } totalBlocksCommitted += uint32(_newBlocksData.length); require(totalCommittedPriorityRequests <= totalOpenPriorityRequests, "j"); } /// @dev 1. Try to send token to _recipients /// @dev 2. On failure: Increment _recipients balance to withdraw. function withdrawOrStoreNFT(Operations.WithdrawNFT memory op) internal { NFTFactory _factory = governance.getNFTFactory(op.creatorAccountId, op.creatorAddress); try _factory.mintNFTFromZkSync{gas: WITHDRAWAL_NFT_GAS_LIMIT}( op.creatorAddress, op.receiver, op.creatorAccountId, op.serialId, op.contentHash, op.tokenId ) { // Save withdrawn nfts for future deposits withdrawnNFTs[op.tokenId] = address(_factory); emit WithdrawalNFT(op.tokenId); } catch { pendingWithdrawnNFTs[op.tokenId] = op; } } /// @dev 1. Try to send token to _recipients /// @dev 2. On failure: Increment _recipients balance to withdraw. function withdrawOrStore( uint16 _tokenId, address _recipient, uint128 _amount ) internal { bytes22 packedBalanceKey = packAddressAndTokenId(_recipient, _tokenId); bool sent = false; if (_tokenId == 0) { address payable toPayable = address(uint160(_recipient)); sent = sendETHNoRevert(toPayable, _amount); } else { address tokenAddr = governance.tokenAddresses(_tokenId); // We use `_transferERC20` here to check that `ERC20` token indeed transferred `_amount` // and fail if token subtracted from zkSync balance more then `_amount` that was requested. // This can happen if token subtracts fee from sender while transferring `_amount` that was requested to transfer. try this._transferERC20{gas: WITHDRAWAL_GAS_LIMIT}(IERC20(tokenAddr), _recipient, _amount, _amount) { sent = true; } catch { sent = false; } } if (sent) { emit Withdrawal(_tokenId, _amount); } else { increaseBalanceToWithdraw(packedBalanceKey, _amount); } } /// @dev Executes one block /// @dev 1. Processes all pending operations (Send Exits, Complete priority requests) /// @dev 2. Finalizes block on Ethereum /// @dev _executedBlockIdx is index in the array of the blocks that we want to execute together function executeOneBlock(ExecuteBlockInfo memory _blockExecuteData, uint32 _executedBlockIdx) internal { // Ensure block was committed require( hashStoredBlockInfo(_blockExecuteData.storedBlock) == storedBlockHashes[_blockExecuteData.storedBlock.blockNumber], "exe10" // executing block should be committed ); require(_blockExecuteData.storedBlock.blockNumber == totalBlocksExecuted + _executedBlockIdx + 1, "k"); // Execute blocks in order bytes32 pendingOnchainOpsHash = EMPTY_STRING_KECCAK; for (uint32 i = 0; i < _blockExecuteData.pendingOnchainOpsPubdata.length; ++i) { bytes memory pubData = _blockExecuteData.pendingOnchainOpsPubdata[i]; Operations.OpType opType = Operations.OpType(uint8(pubData[0])); if (opType == Operations.OpType.PartialExit) { Operations.PartialExit memory op = Operations.readPartialExitPubdata(pubData); // Circuit guarantees that partial exits are available only for fungible tokens require(op.tokenId <= MAX_FUNGIBLE_TOKEN_ID, "mf1"); withdrawOrStore(uint16(op.tokenId), op.owner, op.amount); } else if (opType == Operations.OpType.ForcedExit) { Operations.ForcedExit memory op = Operations.readForcedExitPubdata(pubData); // Circuit guarantees that forced exits are available only for fungible tokens require(op.tokenId <= MAX_FUNGIBLE_TOKEN_ID, "mf2"); withdrawOrStore(uint16(op.tokenId), op.target, op.amount); } else if (opType == Operations.OpType.FullExit) { Operations.FullExit memory op = Operations.readFullExitPubdata(pubData); if (op.tokenId <= MAX_FUNGIBLE_TOKEN_ID) { withdrawOrStore(uint16(op.tokenId), op.owner, op.amount); } else { if (op.amount == 1) { Operations.WithdrawNFT memory withdrawNftOp = Operations.WithdrawNFT( op.nftCreatorAccountId, op.nftCreatorAddress, op.nftSerialId, op.nftContentHash, op.owner, op.tokenId ); withdrawOrStoreNFT(withdrawNftOp); } } } else if (opType == Operations.OpType.WithdrawNFT) { Operations.WithdrawNFT memory op = Operations.readWithdrawNFTPubdata(pubData); withdrawOrStoreNFT(op); } else { revert("l"); // unsupported op in block execution } pendingOnchainOpsHash = Utils.concatHash(pendingOnchainOpsHash, pubData); } require(pendingOnchainOpsHash == _blockExecuteData.storedBlock.pendingOnchainOperationsHash, "m"); // incorrect onchain ops executed } /// @notice Execute blocks, completing priority operations and processing withdrawals. /// @notice 1. Processes all pending operations (Send Exits, Complete priority requests) /// @notice 2. Finalizes block on Ethereum function executeBlocks(ExecuteBlockInfo[] memory _blocksData) external nonReentrant { requireActive(); governance.requireActiveValidator(msg.sender); uint64 priorityRequestsExecuted = 0; uint32 nBlocks = uint32(_blocksData.length); for (uint32 i = 0; i < nBlocks; ++i) { executeOneBlock(_blocksData[i], i); priorityRequestsExecuted += _blocksData[i].storedBlock.priorityOperations; emit BlockVerification(_blocksData[i].storedBlock.blockNumber); } firstPriorityRequestId += priorityRequestsExecuted; totalCommittedPriorityRequests -= priorityRequestsExecuted; totalOpenPriorityRequests -= priorityRequestsExecuted; totalBlocksExecuted += nBlocks; require(totalBlocksExecuted <= totalBlocksProven, "n"); // Can't execute blocks more then committed and proven currently. } /// @notice Blocks commitment verification. /// @notice Only verifies block commitments without any other processing function proveBlocks(StoredBlockInfo[] memory _committedBlocks, ProofInput memory _proof) external nonReentrant { uint32 currentTotalBlocksProven = totalBlocksProven; for (uint256 i = 0; i < _committedBlocks.length; ++i) { require(hashStoredBlockInfo(_committedBlocks[i]) == storedBlockHashes[currentTotalBlocksProven + 1], "o1"); ++currentTotalBlocksProven; require(_proof.commitments[i] & INPUT_MASK == uint256(_committedBlocks[i].commitment) & INPUT_MASK, "o"); // incorrect block commitment in proof } bool success = verifier.verifyAggregatedBlockProof( _proof.recursiveInput, _proof.proof, _proof.vkIndexes, _proof.commitments, _proof.subproofsLimbs ); require(success, "p"); // Aggregated proof verification fail require(currentTotalBlocksProven <= totalBlocksCommitted, "q"); totalBlocksProven = currentTotalBlocksProven; } /// @notice Reverts unverified blocks function revertBlocks(StoredBlockInfo[] memory _blocksToRevert) external { /// All functions delegated to additional contract should NOT be nonReentrant delegateAdditional(); } /// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event. /// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest /// @dev of existed priority requests expiration block number. /// @return bool flag that is true if the Exodus mode must be entered. function activateExodusMode() public returns (bool) { bool trigger = block.number >= priorityRequests[firstPriorityRequestId].expirationBlock && priorityRequests[firstPriorityRequestId].expirationBlock != 0; if (trigger) { if (!exodusMode) { exodusMode = true; emit ExodusMode(); } return true; } else { return false; } } /// @notice Withdraws token from ZkSync to root chain in case of exodus mode. User must provide proof that he owns funds /// @param _storedBlockInfo Last verified block /// @param _owner Owner of the account /// @param _accountId Id of the account in the tree /// @param _proof Proof /// @param _tokenId Verified token id /// @param _amount Amount for owner (must be total amount, not part of it) function performExodus( StoredBlockInfo memory _storedBlockInfo, address _owner, uint32 _accountId, uint32 _tokenId, uint128 _amount, uint32 _nftCreatorAccountId, address _nftCreatorAddress, uint32 _nftSerialId, bytes32 _nftContentHash, uint256[] memory _proof ) external { /// All functions delegated to additional should NOT be nonReentrant delegateAdditional(); } /// @notice Set data for changing pubkey hash using onchain authorization. /// Transaction author (msg.sender) should be L2 account address /// @notice New pubkey hash can be reset, to do that user should send two transactions: /// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer. /// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`. /// @param _pubkeyHash New pubkey hash /// @param _nonce Nonce of the change pubkey L2 transaction function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external { /// All functions delegated to additional contract should NOT be nonReentrant delegateAdditional(); } /// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event /// @param _tokenId Token by id /// @param _amount Token amount /// @param _owner Receiver function registerDeposit( uint16 _tokenId, uint128 _amount, address _owner ) internal { // Priority Queue request Operations.Deposit memory op = Operations.Deposit({ accountId: 0, // unknown at this point owner: _owner, tokenId: _tokenId, amount: _amount }); bytes memory pubData = Operations.writeDepositPubdataForPriorityQueue(op); addPriorityRequest(Operations.OpType.Deposit, pubData); emit Deposit(_tokenId, _amount); } /// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event /// @param _token - token by id /// @param _amount - token amount /// @param _to - address to withdraw to function registerWithdrawal( uint16 _token, uint128 _amount, address payable _to ) internal { bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token); uint128 balance = pendingBalances[packedBalanceKey].balanceToWithdraw; pendingBalances[packedBalanceKey].balanceToWithdraw = balance.sub(_amount); emit Withdrawal(_token, _amount); } /// @dev Gets operations packed in bytes array. Unpacks it and stores onchain operations. /// @dev Priority operations must be committed in the same order as they are in the priority queue. /// @dev NOTE: does not change storage! (only emits events) /// @dev processableOperationsHash - hash of the all operations that needs to be executed (Deposit, Exits, ChangPubKey) /// @dev priorityOperationsProcessed - number of priority operations processed in this block (Deposits, FullExits) /// @dev offsetsCommitment - array where 1 is stored in chunk where onchainOperation begins and other are 0 (used in commitments) function collectOnchainOps(CommitBlockInfo memory _newBlockData) internal view returns ( bytes32 processableOperationsHash, uint64 priorityOperationsProcessed, bytes memory offsetsCommitment ) { bytes memory pubData = _newBlockData.publicData; uint64 uncommittedPriorityRequestsOffset = firstPriorityRequestId + totalCommittedPriorityRequests; priorityOperationsProcessed = 0; processableOperationsHash = EMPTY_STRING_KECCAK; require(pubData.length % CHUNK_BYTES == 0, "A"); // pubdata length must be a multiple of CHUNK_BYTES offsetsCommitment = new bytes(pubData.length / CHUNK_BYTES); for (uint256 i = 0; i < _newBlockData.onchainOperations.length; ++i) { OnchainOperationData memory onchainOpData = _newBlockData.onchainOperations[i]; uint256 pubdataOffset = onchainOpData.publicDataOffset; require(pubdataOffset < pubData.length, "A1"); require(pubdataOffset % CHUNK_BYTES == 0, "B"); // offsets should be on chunks boundaries uint256 chunkId = pubdataOffset / CHUNK_BYTES; require(offsetsCommitment[chunkId] == 0x00, "C"); // offset commitment should be empty offsetsCommitment[chunkId] = bytes1(0x01); Operations.OpType opType = Operations.OpType(uint8(pubData[pubdataOffset])); if (opType == Operations.OpType.Deposit) { bytes memory opPubData = Bytes.slice(pubData, pubdataOffset, DEPOSIT_BYTES); Operations.Deposit memory depositData = Operations.readDepositPubdata(opPubData); checkPriorityOperation(depositData, uncommittedPriorityRequestsOffset + priorityOperationsProcessed); priorityOperationsProcessed++; } else if (opType == Operations.OpType.ChangePubKey) { bytes memory opPubData = Bytes.slice(pubData, pubdataOffset, CHANGE_PUBKEY_BYTES); Operations.ChangePubKey memory op = Operations.readChangePubKeyPubdata(opPubData); if (onchainOpData.ethWitness.length != 0) { bool valid = verifyChangePubkey(onchainOpData.ethWitness, op); require(valid, "D"); // failed to verify change pubkey hash signature } else { bool valid = authFacts[op.owner][op.nonce] == keccak256(abi.encodePacked(op.pubKeyHash)); require(valid, "E"); // new pub key hash is not authenticated properly } } else { bytes memory opPubData; if (opType == Operations.OpType.PartialExit) { opPubData = Bytes.slice(pubData, pubdataOffset, PARTIAL_EXIT_BYTES); } else if (opType == Operations.OpType.ForcedExit) { opPubData = Bytes.slice(pubData, pubdataOffset, FORCED_EXIT_BYTES); } else if (opType == Operations.OpType.WithdrawNFT) { opPubData = Bytes.slice(pubData, pubdataOffset, WITHDRAW_NFT_BYTES); } else if (opType == Operations.OpType.FullExit) { opPubData = Bytes.slice(pubData, pubdataOffset, FULL_EXIT_BYTES); Operations.FullExit memory fullExitData = Operations.readFullExitPubdata(opPubData); checkPriorityOperation( fullExitData, uncommittedPriorityRequestsOffset + priorityOperationsProcessed ); priorityOperationsProcessed++; } else { revert("F"); // unsupported op } processableOperationsHash = Utils.concatHash(processableOperationsHash, opPubData); } } } /// @notice Checks that change operation is correct function verifyChangePubkey(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { Operations.ChangePubkeyType changePkType = Operations.ChangePubkeyType(uint8(_ethWitness[0])); if (changePkType == Operations.ChangePubkeyType.ECRECOVER) { return verifyChangePubkeyECRECOVER(_ethWitness, _changePk); } else if (changePkType == Operations.ChangePubkeyType.CREATE2) { return verifyChangePubkeyCREATE2(_ethWitness, _changePk); } else if (changePkType == Operations.ChangePubkeyType.OldECRECOVER) { return verifyChangePubkeyOldECRECOVER(_ethWitness, _changePk); } else { revert("G"); // Incorrect ChangePubKey type } } /// @notice Checks that signature is valid for pubkey change message /// @param _ethWitness Signature (65 bytes) + 32 bytes of the arbitrary signed data /// @param _changePk Parsed change pubkey operation function verifyChangePubkeyECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { (, bytes memory signature) = Bytes.read(_ethWitness, 1, 65); // offset is 1 because we skip type of ChangePubkey // (, bytes32 additionalData) = Bytes.readBytes32(_ethWitness, offset); bytes32 messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n60", _changePk.pubKeyHash, _changePk.nonce, _changePk.accountId, bytes32(0) ) ); address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash); return recoveredAddress == _changePk.owner && recoveredAddress != address(0); } /// @notice Checks that signature is valid for pubkey change message, old version differs by form of the signed message. /// @param _ethWitness Signature (65 bytes) /// @param _changePk Parsed change pubkey operation function verifyChangePubkeyOldECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { (, bytes memory signature) = Bytes.read(_ethWitness, 1, 65); // offset is 1 because we skip type of ChangePubkey bytes32 messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n152", "Register zkSync pubkey:\n\n", Bytes.bytesToHexASCIIBytes(abi.encodePacked(_changePk.pubKeyHash)), "\n", "nonce: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.nonce)), "\n", "account id: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.accountId)), "\n\n", "Only sign this message for a trusted client!" ) ); address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash); return recoveredAddress == _changePk.owner && recoveredAddress != address(0); } /// @notice Checks that signature is valid for pubkey change message /// @param _ethWitness Create2 deployer address, saltArg, codeHash /// @param _changePk Parsed change pubkey operation function verifyChangePubkeyCREATE2(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk) internal pure returns (bool) { address creatorAddress; bytes32 saltArg; // salt arg is additional bytes that are encoded in the CREATE2 salt bytes32 codeHash; uint256 offset = 1; // offset is 1 because we skip type of ChangePubkey (offset, creatorAddress) = Bytes.readAddress(_ethWitness, offset); (offset, saltArg) = Bytes.readBytes32(_ethWitness, offset); (offset, codeHash) = Bytes.readBytes32(_ethWitness, offset); // salt from CREATE2 specification bytes32 salt = keccak256(abi.encodePacked(saltArg, _changePk.pubKeyHash)); // Address computation according to CREATE2 definition: https://eips.ethereum.org/EIPS/eip-1014 address recoveredAddress = address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), creatorAddress, salt, codeHash))))); // This type of change pubkey can be done only once return recoveredAddress == _changePk.owner && _changePk.nonce == 0; } /// @dev Creates block commitment from its data /// @dev _offsetCommitment - hash of the array where 1 is stored in chunk where onchainOperation begins and 0 for other chunks function createBlockCommitment( StoredBlockInfo memory _previousBlock, CommitBlockInfo memory _newBlockData, bytes memory _offsetCommitment ) internal view returns (bytes32 commitment) { bytes32 hash = sha256(abi.encodePacked(uint256(_newBlockData.blockNumber), uint256(_newBlockData.feeAccount))); hash = sha256(abi.encodePacked(hash, _previousBlock.stateHash)); hash = sha256(abi.encodePacked(hash, _newBlockData.newStateHash)); hash = sha256(abi.encodePacked(hash, uint256(_newBlockData.timestamp))); bytes memory pubdata = abi.encodePacked(_newBlockData.publicData, _offsetCommitment); /// The code below is equivalent to `commitment = sha256(abi.encodePacked(hash, _publicData))` /// We use inline assembly instead of this concise and readable code in order to avoid copying of `_publicData` (which saves ~90 gas per transfer operation). /// Specifically, we perform the following trick: /// First, replace the first 32 bytes of `_publicData` (where normally its length is stored) with the value of `hash`. /// Then, we call `sha256` precompile passing the `_publicData` pointer and the length of the concatenated byte buffer. /// Finally, we put the `_publicData.length` back to its original location (to the first word of `_publicData`). assembly { let hashResult := mload(0x40) let pubDataLen := mload(pubdata) mstore(pubdata, hash) // staticcall to the sha256 precompile at address 0x2 let success := staticcall(gas(), 0x2, pubdata, add(pubDataLen, 0x20), hashResult, 0x20) mstore(pubdata, pubDataLen) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } commitment := mload(hashResult) } } /// @notice Checks that deposit is same as operation in priority queue /// @param _deposit Deposit data /// @param _priorityRequestId Operation's id in priority queue function checkPriorityOperation(Operations.Deposit memory _deposit, uint64 _priorityRequestId) internal view { Operations.OpType priorReqType = priorityRequests[_priorityRequestId].opType; require(priorReqType == Operations.OpType.Deposit, "H"); // incorrect priority op type bytes20 hashedPubdata = priorityRequests[_priorityRequestId].hashedPubData; require(Operations.checkDepositInPriorityQueue(_deposit, hashedPubdata), "I"); } /// @notice Checks that FullExit is same as operation in priority queue /// @param _fullExit FullExit data /// @param _priorityRequestId Operation's id in priority queue function checkPriorityOperation(Operations.FullExit memory _fullExit, uint64 _priorityRequestId) internal view { Operations.OpType priorReqType = priorityRequests[_priorityRequestId].opType; require(priorReqType == Operations.OpType.FullExit, "J"); // incorrect priority op type bytes20 hashedPubdata = priorityRequests[_priorityRequestId].hashedPubData; require(Operations.checkFullExitInPriorityQueue(_fullExit, hashedPubdata), "K"); } /// @notice Checks that current state not is exodus mode function requireActive() internal view { require(!exodusMode, "L"); // exodus mode activated } // Priority queue /// @notice Saves priority request in storage /// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event /// @param _opType Rollup operation type /// @param _pubData Operation pubdata function addPriorityRequest(Operations.OpType _opType, bytes memory _pubData) internal { // Expiration block is: current block number + priority expiration delta uint64 expirationBlock = uint64(block.number + PRIORITY_EXPIRATION); uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests; bytes20 hashedPubData = Utils.hashBytesToBytes20(_pubData); priorityRequests[nextPriorityRequestId] = PriorityOperation({ hashedPubData: hashedPubData, expirationBlock: expirationBlock, opType: _opType }); emit NewPriorityRequest(msg.sender, nextPriorityRequestId, _opType, _pubData, uint256(expirationBlock)); totalOpenPriorityRequests++; } function increaseBalanceToWithdraw(bytes22 _packedBalanceKey, uint128 _amount) internal { uint128 balance = pendingBalances[_packedBalanceKey].balanceToWithdraw; pendingBalances[_packedBalanceKey] = PendingBalance(balance.add(_amount), FILLED_GAS_RESERVE_VALUE); } /// @notice Sends ETH /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendETHNoRevert(address payable _to, uint256 _amount) internal returns (bool) { (bool callSuccess, ) = _to.call{gas: WITHDRAWAL_GAS_LIMIT, value: _amount}(""); return callSuccess; } /// @notice Delegates the call to the additional part of the main contract. /// @notice Should be only use to delegate the external calls as it passes the calldata /// @notice All functions delegated to additional contract should NOT be nonReentrant function delegateAdditional() internal { AdditionalZkSync _target = additionalZkSync; assembly { // The pointer to the free memory slot let ptr := mload(0x40) // Copy function signature and arguments from calldata at zero position into memory at pointer position calldatacopy(ptr, 0x0, calldatasize()) // Delegatecall method of the implementation contract, returns 0 on error let result := delegatecall(gas(), _target, ptr, calldatasize(), 0x0, 0) // Get the size of the last return data let size := returndatasize() // Copy the size length of bytes from return data at zero position to pointer position returndatacopy(ptr, 0x0, size) // Depending on result value switch result case 0 { // End execution and revert state changes revert(ptr, size) } default { // Return data with length of size at pointers position return(ptr, size) } } } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { /// @dev Address of lock flag variable. /// @dev Flag is placed at random memory location to not interfere with Storage contract. uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol // 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; function initializeReentrancyGuard() internal { uint256 lockSlotOldValue; // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange every call to nonReentrant // will be cheaper. assembly { lockSlotOldValue := sload(LOCK_FLAG_ADDRESS) sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED) } // Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict require(lockSlotOldValue == 0, "1B"); } /** * @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() { uint256 _status; assembly { _status := sload(LOCK_FLAG_ADDRESS) } // On the first call to nonReentrant, _notEntered will be true require(_status == _NOT_ENTERED); // Any calls to nonReentrant after this point will fail assembly { sstore(LOCK_FLAG_ADDRESS, _ENTERED) } _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) assembly { sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED) } } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.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, "14"); 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, "v"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "15"); 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, "x"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "y"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.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 SafeMathUInt128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "12"); 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(uint128 a, uint128 b) internal pure returns (uint128) { return sub(a, b, "aa"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 c = a * b; require(c / a == b, "13"); 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(uint128 a, uint128 b) internal pure returns (uint128) { return div(a, b, "ac"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { return mod(a, b, "ad"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. * * _Available since v2.5.0._ */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "16"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "17"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "18"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "19"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "1a"); return uint8(value); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./IERC20.sol"; import "./Bytes.sol"; library Utils { /// @notice Returns lesser of two values function minU32(uint32 a, uint32 b) internal pure returns (uint32) { return a < b ? a : b; } /// @notice Returns lesser of two values function minU64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } /// @notice Sends tokens /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transfer` to this token may return (bool) or nothing /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendERC20( IERC20 _token, address _to, uint256 _amount ) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount)); // `transfer` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Transfers token from one address to another /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing /// @param _token Token address /// @param _from Address of sender /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function transferFromERC20( IERC20 _token, address _from, address _to, uint256 _amount ) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount)); // `transferFrom` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Recovers signer's address from ethereum signature for given message /// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1) /// @param _messageHash signed message hash. /// @return address of the signer function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash) internal pure returns (address) { require(_signature.length == 65, "P"); // incorrect signature length bytes32 signR; bytes32 signS; uint8 signV; assembly { signR := mload(add(_signature, 32)) signS := mload(add(_signature, 64)) signV := byte(0, mload(add(_signature, 96))) } return ecrecover(_messageHash, signV, signR, signS); } /// @notice Returns new_hash = hash(old_hash + bytes) function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) { bytes32 result; assembly { let bytesLen := add(mload(_bytes), 32) mstore(_bytes, _hash) result := keccak256(_bytes, bytesLen) } return result; } function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) { return bytes20(uint160(uint256(keccak256(_bytes)))); } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 // solhint-disable max-states-count import "./IERC20.sol"; import "./Governance.sol"; import "./Verifier.sol"; import "./Operations.sol"; import "./NFTFactory.sol"; import "./AdditionalZkSync.sol"; /// @title zkSync storage contract /// @author Matter Labs contract Storage { /// @dev Flag indicates that upgrade preparation status is active /// @dev Will store false in case of not active upgrade mode bool internal upgradePreparationActive; /// @dev Upgrade preparation activation timestamp (as seconds since unix epoch) /// @dev Will be equal to zero in case of not active upgrade mode uint256 internal upgradePreparationActivationTime; /// @dev Verifier contract. Used to verify block proof and exit proof Verifier internal verifier; /// @dev Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list Governance internal governance; uint8 internal constant FILLED_GAS_RESERVE_VALUE = 0xff; // we use it to set gas revert value so slot will not be emptied with 0 balance struct PendingBalance { uint128 balanceToWithdraw; uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value } /// @dev Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw mapping(bytes22 => PendingBalance) internal pendingBalances; // @dev Pending withdrawals are not used in this version struct PendingWithdrawalDEPRECATED { address to; uint16 tokenId; } mapping(uint32 => PendingWithdrawalDEPRECATED) internal pendingWithdrawalsDEPRECATED; uint32 internal firstPendingWithdrawalIndexDEPRECATED; uint32 internal numberOfPendingWithdrawalsDEPRECATED; /// @dev Total number of executed blocks i.e. blocks[totalBlocksExecuted] points at the latest executed block (block 0 is genesis) uint32 public totalBlocksExecuted; /// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block uint32 public totalBlocksCommitted; /// @Old rollup block stored data - not used in current version /// @member validator Block producer /// @member committedAtBlock ETH block number at which this block was committed /// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks /// @member priorityOperations Total number of priority operations for this block /// @member commitment Hash of the block circuit commitment /// @member stateRoot New tree root hash /// /// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html struct BlockDEPRECATED { uint32 committedAtBlock; uint64 priorityOperations; uint32 chunks; bytes32 withdrawalsDataHash; // can be restricted to 16 bytes to reduce number of required storage slots bytes32 commitment; bytes32 stateRoot; } mapping(uint32 => BlockDEPRECATED) internal blocksDEPRECATED; /// @dev Flag indicates that a user has exited in the exodus mode certain token balance (per account id and tokenId) mapping(uint32 => mapping(uint32 => bool)) internal performedExodus; /// @dev Flag indicates that exodus (mass exit) mode is triggered /// @dev Once it was raised, it can not be cleared again, and all users must exit bool public exodusMode; /// @dev User authenticated fact hashes for some nonce. mapping(address => mapping(uint32 => bytes32)) public authFacts; /// @notice Old Priority Operation container /// @member opType Priority operation type /// @member pubData Priority operation public data /// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before) struct PriorityOperationDEPRECATED { Operations.OpType opType; bytes pubData; uint256 expirationBlock; } /// @dev Priority Requests mapping (request id - operation) /// @dev Contains op type, pubdata and expiration block of unsatisfied requests. /// @dev Numbers are in order of requests receiving mapping(uint64 => PriorityOperationDEPRECATED) internal priorityRequestsDEPRECATED; /// @dev First open priority request id uint64 public firstPriorityRequestId; /// @dev Total number of requests uint64 public totalOpenPriorityRequests; /// @dev Total number of committed requests. /// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big uint64 internal totalCommittedPriorityRequests; /// @notice Packs address and token id into single word to use as a key in balances mapping function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) { return bytes22((uint176(_address) | (uint176(_tokenId) << 160))); } /// @Rollup block stored data /// @member blockNumber Rollup block number /// @member priorityOperations Number of priority operations processed /// @member pendingOnchainOperationsHash Hash of all operations that must be processed after verify /// @member timestamp Rollup block timestamp, have the same format as Ethereum block constant /// @member stateHash Root hash of the rollup state /// @member commitment Verified input for the zkSync circuit struct StoredBlockInfo { uint32 blockNumber; uint64 priorityOperations; bytes32 pendingOnchainOperationsHash; uint256 timestamp; bytes32 stateHash; bytes32 commitment; } /// @notice Returns the keccak hash of the ABI-encoded StoredBlockInfo function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) internal pure returns (bytes32) { return keccak256(abi.encode(_storedBlockInfo)); } /// @dev Stored hashed StoredBlockInfo for some block number mapping(uint32 => bytes32) public storedBlockHashes; /// @dev Total blocks proven. uint32 public totalBlocksProven; /// @notice Priority Operation container /// @member hashedPubData Hashed priority operation public data /// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before) /// @member opType Priority operation type struct PriorityOperation { bytes20 hashedPubData; uint64 expirationBlock; Operations.OpType opType; } /// @dev Priority Requests mapping (request id - operation) /// @dev Contains op type, pubdata and expiration block of unsatisfied requests. /// @dev Numbers are in order of requests receiving mapping(uint64 => PriorityOperation) internal priorityRequests; /// @dev Timer for authFacts entry reset (address, nonce -> timer). /// @dev Used when user wants to reset `authFacts` for some nonce. mapping(address => mapping(uint32 => uint256)) internal authFactsResetTimer; mapping(uint32 => address) internal withdrawnNFTs; mapping(uint32 => Operations.WithdrawNFT) internal pendingWithdrawnNFTs; AdditionalZkSync internal additionalZkSync; /// @dev Upgrade notice period, possibly shorten by the security council uint256 internal approvedUpgradeNoticePeriod; /// @dev Upgrade start timestamp (as seconds since unix epoch) /// @dev Will be equal to zero in case of not active upgrade mode uint256 internal upgradeStartTimestamp; /// @dev Stores boolean flags which means the confirmations of the upgrade for each member of security council /// @dev Will store zeroes in case of not active upgrade mode mapping(uint256 => bool) internal securityCouncilApproves; uint256 internal numberOfApprovalsFromSecurityCouncil; } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title zkSync configuration constants /// @author Matter Labs contract Config { /// @dev ERC20 tokens and ETH withdrawals gas limit, used only for complete withdrawals uint256 internal constant WITHDRAWAL_GAS_LIMIT = 100000; /// @dev NFT withdrawals gas limit, used only for complete withdrawals uint256 internal constant WITHDRAWAL_NFT_GAS_LIMIT = 300000; /// @dev Bytes in one chunk uint8 internal constant CHUNK_BYTES = 10; /// @dev zkSync address length uint8 internal constant ADDRESS_BYTES = 20; uint8 internal constant PUBKEY_HASH_BYTES = 20; /// @dev Public key bytes length uint8 internal constant PUBKEY_BYTES = 32; /// @dev Ethereum signature r/s bytes length uint8 internal constant ETH_SIGN_RS_BYTES = 32; /// @dev Success flag bytes length uint8 internal constant SUCCESS_FLAG_BYTES = 1; /// @dev Max amount of tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 internal constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 1023; /// @dev Max account id that could be registered in the network uint32 internal constant MAX_ACCOUNT_ID = 16777215; /// @dev Expected average period of block creation uint256 internal constant BLOCK_PERIOD = 15 seconds; /// @dev ETH blocks verification expectation /// @dev Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN. /// @dev If set to 0 validator can revert blocks at any time. uint256 internal constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD; uint256 internal constant NOOP_BYTES = 1 * CHUNK_BYTES; uint256 internal constant DEPOSIT_BYTES = 6 * CHUNK_BYTES; uint256 internal constant MINT_NFT_BYTES = 5 * CHUNK_BYTES; uint256 internal constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES; uint256 internal constant PARTIAL_EXIT_BYTES = 6 * CHUNK_BYTES; uint256 internal constant TRANSFER_BYTES = 2 * CHUNK_BYTES; uint256 internal constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES; uint256 internal constant WITHDRAW_NFT_BYTES = 10 * CHUNK_BYTES; /// @dev Full exit operation length uint256 internal constant FULL_EXIT_BYTES = 11 * CHUNK_BYTES; /// @dev ChangePubKey operation length uint256 internal constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES; /// @dev Expiration delta for priority request to be satisfied (in seconds) /// @dev NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD) /// @dev otherwise incorrect block with priority op could not be reverted. uint256 internal constant PRIORITY_EXPIRATION_PERIOD = 3 days; /// @dev Expiration delta for priority request to be satisfied (in ETH blocks) uint256 internal constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD/BLOCK_PERIOD; /// @dev Maximum number of priority request to clear during verifying the block /// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots /// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure uint64 internal constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6; /// @dev Reserved time for users to send full exit priority operation in case of an upgrade (in seconds) uint256 internal constant MASS_FULL_EXIT_PERIOD = 9 days; /// @dev Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds) uint256 internal constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days; /// @dev Notice period before activation preparation status of upgrade mode (in seconds) /// @dev NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it. uint256 internal constant UPGRADE_NOTICE_PERIOD = MASS_FULL_EXIT_PERIOD+PRIORITY_EXPIRATION_PERIOD+TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT; /// @dev Timestamp - seconds since unix epoch uint256 internal constant COMMIT_TIMESTAMP_NOT_OLDER = 24 hours; /// @dev Maximum available error between real commit block timestamp and analog used in the verifier (in seconds) /// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 15 seconds) uint256 internal constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes; /// @dev Bit mask to apply for verifier public input before verifying. uint256 internal constant INPUT_MASK = 14474011154664524427946373126085988481658748083205070504932198000989141204991; /// @dev Auth fact reset timelock. uint256 internal constant AUTH_FACT_RESET_TIMELOCK = 1 days; /// @dev Max deposit of ERC20 token that is possible to deposit uint128 internal constant MAX_DEPOSIT_AMOUNT = 20282409603651670423947251286015; uint32 internal constant SPECIAL_ACCOUNT_ID = 16777215; address internal constant SPECIAL_ACCOUNT_ADDRESS = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF); uint32 internal constant SPECIAL_NFT_TOKEN_ID = 2147483646; uint32 internal constant MAX_FUNGIBLE_TOKEN_ID = 65535; uint256 internal constant SECURITY_COUNCIL_MEMBERS_NUMBER = 15; } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Upgradeable.sol"; import "./Operations.sol"; /// @title zkSync events /// @author Matter Labs interface Events { /// @notice Event emitted when a block is committed event BlockCommit(uint32 indexed blockNumber); /// @notice Event emitted when a block is verified event BlockVerification(uint32 indexed blockNumber); /// @notice Event emitted when user funds are withdrawn from the zkSync contract event Withdrawal(uint16 indexed tokenId, uint128 amount); /// @notice Event emitted when user NFT is withdrawn from the zkSync contract event WithdrawalNFT(uint32 indexed tokenId); /// @notice Event emitted when user funds are deposited to the zkSync contract event Deposit(uint16 indexed tokenId, uint128 amount); /// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash) event FactAuth(address indexed sender, uint32 nonce, bytes fact); /// @notice Event emitted when blocks are reverted event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted); /// @notice Exodus mode entered event event ExodusMode(); /// @notice New priority request event. Emitted when a request is placed into mapping event NewPriorityRequest( address sender, uint64 serialId, Operations.OpType opType, bytes pubData, uint256 expirationBlock ); /// @notice Deposit committed event. event DepositCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Full exit committed event. event FullExitCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Notice period changed event NoticePeriodChange(uint256 newNoticePeriod); } /// @title Upgrade events /// @author Matter Labs interface UpgradeEvents { /// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts event NewUpgradable(uint256 indexed versionId, address indexed upgradeable); /// @notice Upgrade mode enter event event NoticePeriodStart( uint256 indexed versionId, address[] newTargets, uint256 noticePeriod // notice period (in seconds) ); /// @notice Upgrade mode cancel event event UpgradeCancel(uint256 indexed versionId); /// @notice Upgrade mode preparation status event event PreparationStart(uint256 indexed versionId); /// @notice Upgrade mode complete event event UpgradeComplete(uint256 indexed versionId, address[] newTargets); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 // Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word) // implements the following algorithm: // f(bytes memory input, uint offset) -> X out // where byte representation of out is N bytes from input at the given offset // 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N] // W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N // 2) We load W from memory into out, last N bytes of W are placed into out library Bytes { function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 2); } function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 3); } function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 4); } function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint256(self), 16); } // Copies 'len' lower bytes from 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'. function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) { require(byteLength <= 32, "Q"); bts = new bytes(byteLength); // Even though the bytes will allocate a full word, we don't want // any potential garbage bytes in there. uint256 data = self << ((32 - byteLength) * 8); assembly { mstore( add(bts, 32), // BYTES_HEADER_SIZE data ) } } // Copies 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length '20'. function toBytesFromAddress(address self) internal pure returns (bytes memory bts) { bts = toBytesFromUIntTruncated(uint256(self), 20); } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 20) function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) { uint256 offset = _start + 20; require(self.length >= offset, "R"); assembly { addr := mload(add(self, offset)) } } // Reasoning about why this function works is similar to that of other similar functions, except NOTE below. // NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types // NOTE: theoretically possible overflow of (_start + 20) function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) { require(self.length >= (_start + 20), "S"); assembly { r := mload(add(add(self, 0x20), _start)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x2) function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) { uint256 offset = _start + 0x2; require(_bytes.length >= offset, "T"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x3) function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) { uint256 offset = _start + 0x3; require(_bytes.length >= offset, "U"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x4) function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) { uint256 offset = _start + 0x4; require(_bytes.length >= offset, "V"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x10) function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) { uint256 offset = _start + 0x10; require(_bytes.length >= offset, "W"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x14) function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) { uint256 offset = _start + 0x14; require(_bytes.length >= offset, "X"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x20) function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) { uint256 offset = _start + 0x20; require(_bytes.length >= offset, "Y"); assembly { r := mload(add(_bytes, offset)) } } // Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228 // Get slice from bytes arrays // Returns the newly created 'bytes memory' // NOTE: theoretically possible overflow of (_start + _length) function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes bytes memory tempBytes = new bytes(_length); if (_length != 0) { assembly { let slice_curr := add(tempBytes, 0x20) let slice_end := add(slice_curr, _length) for { let array_current := add(_bytes, add(_start, 0x20)) } lt(slice_curr, slice_end) { slice_curr := add(slice_curr, 0x20) array_current := add(array_current, 0x20) } { mstore(slice_curr, mload(array_current)) } } } return tempBytes; } /// Reads byte stream /// @return newOffset - offset + amount of bytes read /// @return data - actually read data // NOTE: theoretically possible overflow of (_offset + _length) function read( bytes memory _data, uint256 _offset, uint256 _length ) internal pure returns (uint256 newOffset, bytes memory data) { data = slice(_data, _offset, _length); newOffset = _offset + _length; } // NOTE: theoretically possible overflow of (_offset + 1) function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bool r) { newOffset = _offset + 1; r = uint8(_data[_offset]) != 0; } // NOTE: theoretically possible overflow of (_offset + 1) function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint8 r) { newOffset = _offset + 1; r = uint8(_data[_offset]); } // NOTE: theoretically possible overflow of (_offset + 2) function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint16 r) { newOffset = _offset + 2; r = bytesToUInt16(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 3) function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint24 r) { newOffset = _offset + 3; r = bytesToUInt24(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 4) function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint32 r) { newOffset = _offset + 4; r = bytesToUInt32(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 16) function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint128 r) { newOffset = _offset + 16; r = bytesToUInt128(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint160 r) { newOffset = _offset + 20; r = bytesToUInt160(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, address r) { newOffset = _offset + 20; r = bytesToAddress(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bytes20 r) { newOffset = _offset + 20; r = bytesToBytes20(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 32) function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bytes32 r) { newOffset = _offset + 32; r = bytesToBytes32(_data, _offset); } /// Trim bytes into single word function trim(bytes memory _data, uint256 _newLength) internal pure returns (uint256 r) { require(_newLength <= 0x20, "10"); // new_length is longer than word require(_data.length >= _newLength, "11"); // data is to short uint256 a; assembly { a := mload(add(_data, 0x20)) // load bytes into uint256 } return a >> ((0x20 - _newLength) * 8); } // Helper function for hex conversion. function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) { require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range. // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8))); } // Convert bytes to ASCII hex representation function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) { bytes memory outStringBytes = new bytes(_input.length * 2); // code in `assembly` construction is equivalent of the next code: // for (uint i = 0; i < _input.length; ++i) { // outStringBytes[i*2] = halfByteToHex(_input[i] >> 4); // outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f); // } assembly { let input_curr := add(_input, 0x20) let input_end := add(input_curr, mload(_input)) for { let out_curr := add(outStringBytes, 0x20) } lt(input_curr, input_end) { input_curr := add(input_curr, 0x01) out_curr := add(out_curr, 0x02) } { let curr_input_byte := shr(0xf8, mload(input_curr)) // here outStringByte from each half of input byte calculates by the next: // // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. // outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8))) mstore( out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) mstore( add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) } } return outStringBytes; } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Bytes.sol"; import "./Utils.sol"; /// @title zkSync operations tools library Operations { // Circuit ops and their pubdata (chunks * bytes) /// @notice zkSync circuit operation type enum OpType { Noop, Deposit, TransferToNew, PartialExit, _CloseAccount, // used for correct op id offset Transfer, FullExit, ChangePubKey, ForcedExit, MintNFT, WithdrawNFT, Swap } // Byte lengths uint8 internal constant OP_TYPE_BYTES = 1; uint8 internal constant TOKEN_BYTES = 4; uint8 internal constant PUBKEY_BYTES = 32; uint8 internal constant NONCE_BYTES = 4; uint8 internal constant PUBKEY_HASH_BYTES = 20; uint8 internal constant ADDRESS_BYTES = 20; uint8 internal constant CONTENT_HASH_BYTES = 32; /// @dev Packed fee bytes lengths uint8 internal constant FEE_BYTES = 2; /// @dev zkSync account id bytes lengths uint8 internal constant ACCOUNT_ID_BYTES = 4; /// @dev zkSync nft serial id bytes lengths uint8 internal constant NFT_SERIAL_ID_BYTES = 4; uint8 internal constant AMOUNT_BYTES = 16; /// @dev Signature (for example full exit signature) bytes length uint8 internal constant SIGNATURE_BYTES = 64; // Deposit pubdata struct Deposit { // uint8 opType uint32 accountId; uint32 tokenId; uint128 amount; address owner; } uint256 internal constant PACKED_DEPOSIT_PUBDATA_BYTES = OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES; /// Deserialize deposit pubdata function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "N"); // reading invalid deposit pubdata size } /// Serialize deposit pubdata function writeDepositPubdataForPriorityQueue(Deposit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( uint8(OpType.Deposit), bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenId, // tokenId op.amount, // amount op.owner // owner ); } /// @notice Write deposit pubdata for priority queue check. function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) { return Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata; } // FullExit pubdata struct FullExit { // uint8 opType uint32 accountId; address owner; uint32 tokenId; uint128 amount; uint32 nftCreatorAccountId; address nftCreatorAddress; uint32 nftSerialId; bytes32 nftContentHash; } uint256 public constant PACKED_FULL_EXIT_PUBDATA_BYTES = OP_TYPE_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ACCOUNT_ID_BYTES + ADDRESS_BYTES + NFT_SERIAL_ID_BYTES + CONTENT_HASH_BYTES; function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount (offset, parsed.nftCreatorAccountId) = Bytes.readUInt32(_data, offset); // nftCreatorAccountId (offset, parsed.nftCreatorAddress) = Bytes.readAddress(_data, offset); // nftCreatorAddress (offset, parsed.nftSerialId) = Bytes.readUInt32(_data, offset); // nftSerialId (offset, parsed.nftContentHash) = Bytes.readBytes32(_data, offset); // nftContentHash require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "O"); // reading invalid full exit pubdata size } function writeFullExitPubdataForPriorityQueue(FullExit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( uint8(OpType.FullExit), op.accountId, // accountId op.owner, // owner op.tokenId, // tokenId uint128(0), // amount -- ignored uint32(0), // nftCreatorAccountId -- ignored address(0), // nftCreatorAddress -- ignored uint32(0), // nftSerialId -- ignored bytes32(0) // nftContentHash -- ignored ); } function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) { return Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata; } // PartialExit pubdata struct PartialExit { //uint8 opType; -- present in pubdata, ignored at serialization //uint32 accountId; -- present in pubdata, ignored at serialization uint32 tokenId; uint128 amount; //uint16 fee; -- present in pubdata, ignored at serialization address owner; } function readPartialExitPubdata(bytes memory _data) internal pure returns (PartialExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES; // opType + accountId (ignored) (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount offset += FEE_BYTES; // fee (ignored) (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner } // ForcedExit pubdata struct ForcedExit { //uint8 opType; -- present in pubdata, ignored at serialization //uint32 initiatorAccountId; -- present in pubdata, ignored at serialization //uint32 targetAccountId; -- present in pubdata, ignored at serialization uint32 tokenId; uint128 amount; //uint16 fee; -- present in pubdata, ignored at serialization address target; } function readForcedExitPubdata(bytes memory _data) internal pure returns (ForcedExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES * 2; // opType + initiatorAccountId + targetAccountId (ignored) (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount offset += FEE_BYTES; // fee (ignored) (offset, parsed.target) = Bytes.readAddress(_data, offset); // target } // ChangePubKey enum ChangePubkeyType {ECRECOVER, CREATE2, OldECRECOVER} struct ChangePubKey { // uint8 opType; -- present in pubdata, ignored at serialization uint32 accountId; bytes20 pubKeyHash; address owner; uint32 nonce; //uint32 tokenId; -- present in pubdata, ignored at serialization //uint16 fee; -- present in pubdata, ignored at serialization } function readChangePubKeyPubdata(bytes memory _data) internal pure returns (ChangePubKey memory parsed) { uint256 offset = OP_TYPE_BYTES; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce } struct WithdrawNFT { //uint8 opType; -- present in pubdata, ignored at serialization //uint32 accountId; -- present in pubdata, ignored at serialization uint32 creatorAccountId; address creatorAddress; uint32 serialId; bytes32 contentHash; address receiver; uint32 tokenId; //uint32 feeTokenId; //uint16 fee; -- present in pubdata, ignored at serialization } function readWithdrawNFTPubdata(bytes memory _data) internal pure returns (WithdrawNFT memory parsed) { uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES; // opType + accountId (ignored) (offset, parsed.creatorAccountId) = Bytes.readUInt32(_data, offset); (offset, parsed.creatorAddress) = Bytes.readAddress(_data, offset); (offset, parsed.serialId) = Bytes.readUInt32(_data, offset); (offset, parsed.contentHash) = Bytes.readBytes32(_data, offset); (offset, parsed.receiver) = Bytes.readAddress(_data, offset); (offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it) /// @author Matter Labs interface UpgradeableMaster { /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint256); /// @notice Notifies contract that notice period started function upgradeNoticePeriodStarted() external; /// @notice Notifies contract that upgrade preparation status is activated function upgradePreparationStarted() external; /// @notice Notifies contract that upgrade canceled function upgradeCanceled() external; /// @notice Notifies contract that upgrade finishes function upgradeFinishes() external; /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool); } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Ownable.sol"; import "./Config.sol"; /// @title Regenesis Multisig contract /// @author Matter Labs contract RegenesisMultisig is Ownable, Config { event CandidateAccepted(bytes32 oldRootHash, bytes32 newRootHash); event CandidateApproval(uint256 currentApproval); bytes32 public oldRootHash; bytes32 public newRootHash; bytes32 public candidateOldRootHash; bytes32 public candidateNewRootHash; /// @dev Stores boolean flags which means the confirmations of the upgrade for each member of security council mapping(uint256 => bool) internal securityCouncilApproves; uint256 internal numberOfApprovalsFromSecurityCouncil; uint256 securityCouncilThreshold; constructor(uint256 threshold) Ownable(msg.sender) { securityCouncilThreshold = threshold; } function submitHash(bytes32 _oldRootHash, bytes32 _newRootHash) external { // Only zkSync team can submit the hashes require(msg.sender == getMaster(), "1"); candidateOldRootHash = _oldRootHash; candidateNewRootHash = _newRootHash; oldRootHash = bytes32(0); newRootHash = bytes32(0); for (uint256 i = 0; i < SECURITY_COUNCIL_MEMBERS_NUMBER; ++i) { securityCouncilApproves[i] = false; } numberOfApprovalsFromSecurityCouncil = 0; } function approveHash(bytes32 _oldRootHash, bytes32 _newRootHash) external { require(_oldRootHash == candidateOldRootHash, "2"); require(_newRootHash == candidateNewRootHash, "3"); address payable[SECURITY_COUNCIL_MEMBERS_NUMBER] memory SECURITY_COUNCIL_MEMBERS = [0xa2602ea835E03fb39CeD30B43d6b6EAf6aDe1769,0x9D5d6D4BaCCEDf6ECE1883456AA785dc996df607,0x002A5dc50bbB8d5808e418Aeeb9F060a2Ca17346,0x71E805aB236c945165b9Cd0bf95B9f2F0A0488c3,0x76C6cE74EAb57254E785d1DcC3f812D274bCcB11,0xFBfF3FF69D65A9103Bf4fdBf988f5271D12B3190,0xAfC2F2D803479A2AF3A72022D54cc0901a0ec0d6,0x4d1E3089042Ab3A93E03CA88B566b99Bd22438C6,0x19eD6cc20D44e5cF4Bb4894F50162F72402d8567,0x39415255619783A2E71fcF7d8f708A951d92e1b6,0x399a6a13D298CF3F41a562966C1a450136Ea52C2,0xee8AE1F1B4B1E1956C8Bda27eeBCE54Cf0bb5eaB,0xe7CCD4F3feA7df88Cf9B59B30f738ec1E049231f,0xA093284c707e207C36E3FEf9e0B6325fd9d0e33B,0x225d3822De44E58eE935440E0c0B829C4232086e]; for (uint256 id = 0; id < SECURITY_COUNCIL_MEMBERS_NUMBER; ++id) { if (SECURITY_COUNCIL_MEMBERS[id] == msg.sender) { require(securityCouncilApproves[id] == false); securityCouncilApproves[id] = true; numberOfApprovalsFromSecurityCouncil++; emit CandidateApproval(numberOfApprovalsFromSecurityCouncil); // It is ok to check for strict equality since the numberOfApprovalsFromSecurityCouncil // is increased by one at a time. It is better to do so not to emit the // CandidateAccepted event more than once if (numberOfApprovalsFromSecurityCouncil == securityCouncilThreshold) { oldRootHash = candidateOldRootHash; newRootHash = candidateNewRootHash; emit CandidateAccepted(oldRootHash, newRootHash); } } } } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; /// @title zkSync additional main contract /// @author Matter Labs contract AdditionalZkSync is Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; function increaseBalanceToWithdraw(bytes22 _packedBalanceKey, uint128 _amount) internal { uint128 balance = pendingBalances[_packedBalanceKey].balanceToWithdraw; pendingBalances[_packedBalanceKey] = PendingBalance(balance.add(_amount), FILLED_GAS_RESERVE_VALUE); } /// @notice Withdraws token from ZkSync to root chain in case of exodus mode. User must provide proof that he owns funds /// @param _storedBlockInfo Last verified block /// @param _owner Owner of the account /// @param _accountId Id of the account in the tree /// @param _proof Proof /// @param _tokenId Verified token id /// @param _amount Amount for owner (must be total amount, not part of it) function performExodus( StoredBlockInfo memory _storedBlockInfo, address _owner, uint32 _accountId, uint32 _tokenId, uint128 _amount, uint32 _nftCreatorAccountId, address _nftCreatorAddress, uint32 _nftSerialId, bytes32 _nftContentHash, uint256[] memory _proof ) external { require(_accountId <= MAX_ACCOUNT_ID, "e"); require(_accountId != SPECIAL_ACCOUNT_ID, "v"); require(_tokenId < SPECIAL_NFT_TOKEN_ID, "T"); require(exodusMode, "s"); // must be in exodus mode require(!performedExodus[_accountId][_tokenId], "t"); // already exited require(storedBlockHashes[totalBlocksExecuted] == hashStoredBlockInfo(_storedBlockInfo), "u"); // incorrect stored block info bool proofCorrect = verifier.verifyExitProof( _storedBlockInfo.stateHash, _accountId, _owner, _tokenId, _amount, _nftCreatorAccountId, _nftCreatorAddress, _nftSerialId, _nftContentHash, _proof ); require(proofCorrect, "x"); if (_tokenId <= MAX_FUNGIBLE_TOKEN_ID) { bytes22 packedBalanceKey = packAddressAndTokenId(_owner, uint16(_tokenId)); increaseBalanceToWithdraw(packedBalanceKey, _amount); } else { require(_amount != 0, "Z"); // Unsupported nft amount Operations.WithdrawNFT memory withdrawNftOp = Operations.WithdrawNFT( _nftCreatorAccountId, _nftCreatorAddress, _nftSerialId, _nftContentHash, _owner, _tokenId ); pendingWithdrawnNFTs[_tokenId] = withdrawNftOp; } performedExodus[_accountId][_tokenId] = true; } function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external { require(exodusMode, "8"); // exodus mode not active uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n); require(toProcess > 0, "9"); // no deposits to process uint64 currentDepositIdx = 0; for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) { if (priorityRequests[id].opType == Operations.OpType.Deposit) { bytes memory depositPubdata = _depositsPubdata[currentDepositIdx]; require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a"); ++currentDepositIdx; Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata); bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, uint16(op.tokenId)); pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount; } delete priorityRequests[id]; } firstPriorityRequestId += toProcess; totalOpenPriorityRequests -= toProcess; } uint256 internal constant SECURITY_COUNCIL_2_WEEKS_THRESHOLD = 8; uint256 internal constant SECURITY_COUNCIL_1_WEEK_THRESHOLD = 10; uint256 internal constant SECURITY_COUNCIL_3_DAYS_THRESHOLD = 12; function cutUpgradeNoticePeriod() external { address payable[SECURITY_COUNCIL_MEMBERS_NUMBER] memory SECURITY_COUNCIL_MEMBERS = [0xa2602ea835E03fb39CeD30B43d6b6EAf6aDe1769,0x9D5d6D4BaCCEDf6ECE1883456AA785dc996df607,0x002A5dc50bbB8d5808e418Aeeb9F060a2Ca17346,0x71E805aB236c945165b9Cd0bf95B9f2F0A0488c3,0x76C6cE74EAb57254E785d1DcC3f812D274bCcB11,0xFBfF3FF69D65A9103Bf4fdBf988f5271D12B3190,0xAfC2F2D803479A2AF3A72022D54cc0901a0ec0d6,0x4d1E3089042Ab3A93E03CA88B566b99Bd22438C6,0x19eD6cc20D44e5cF4Bb4894F50162F72402d8567,0x39415255619783A2E71fcF7d8f708A951d92e1b6,0x399a6a13D298CF3F41a562966C1a450136Ea52C2,0xee8AE1F1B4B1E1956C8Bda27eeBCE54Cf0bb5eaB,0xe7CCD4F3feA7df88Cf9B59B30f738ec1E049231f,0xA093284c707e207C36E3FEf9e0B6325fd9d0e33B,0x225d3822De44E58eE935440E0c0B829C4232086e]; for (uint256 id = 0; id < SECURITY_COUNCIL_MEMBERS_NUMBER; ++id) { if (SECURITY_COUNCIL_MEMBERS[id] == msg.sender) { require(upgradeStartTimestamp != 0); require(securityCouncilApproves[id] == false); securityCouncilApproves[id] = true; numberOfApprovalsFromSecurityCouncil++; if (numberOfApprovalsFromSecurityCouncil == SECURITY_COUNCIL_2_WEEKS_THRESHOLD) { if (approvedUpgradeNoticePeriod > 2 weeks) { approvedUpgradeNoticePeriod = 2 weeks; emit NoticePeriodChange(approvedUpgradeNoticePeriod); } } else if (numberOfApprovalsFromSecurityCouncil == SECURITY_COUNCIL_1_WEEK_THRESHOLD) { if (approvedUpgradeNoticePeriod > 1 weeks) { approvedUpgradeNoticePeriod = 1 weeks; emit NoticePeriodChange(approvedUpgradeNoticePeriod); } } else if (numberOfApprovalsFromSecurityCouncil == SECURITY_COUNCIL_3_DAYS_THRESHOLD) { if (approvedUpgradeNoticePeriod > 3 days) { approvedUpgradeNoticePeriod = 3 days; emit NoticePeriodChange(approvedUpgradeNoticePeriod); } } break; } } } /// @notice Set data for changing pubkey hash using onchain authorization. /// Transaction author (msg.sender) should be L2 account address /// @notice New pubkey hash can be reset, to do that user should send two transactions: /// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer. /// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`. /// @param _pubkeyHash New pubkey hash /// @param _nonce Nonce of the change pubkey L2 transaction function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external { require(_pubkeyHash.length == PUBKEY_HASH_BYTES, "y"); // PubKeyHash should be 20 bytes. if (authFacts[msg.sender][_nonce] == bytes32(0)) { authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash); } else { uint256 currentResetTimer = authFactsResetTimer[msg.sender][_nonce]; if (currentResetTimer == 0) { authFactsResetTimer[msg.sender][_nonce] = block.timestamp; } else { require(block.timestamp.sub(currentResetTimer) >= AUTH_FACT_RESET_TIMELOCK, "z"); authFactsResetTimer[msg.sender][_nonce] = 0; authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash); } } } /// @notice Reverts unverified blocks function revertBlocks(StoredBlockInfo[] memory _blocksToRevert) external { governance.requireActiveValidator(msg.sender); uint32 blocksCommitted = totalBlocksCommitted; uint32 blocksToRevert = Utils.minU32(uint32(_blocksToRevert.length), blocksCommitted - totalBlocksExecuted); uint64 revertedPriorityRequests = 0; for (uint32 i = 0; i < blocksToRevert; ++i) { StoredBlockInfo memory storedBlockInfo = _blocksToRevert[i]; require(storedBlockHashes[blocksCommitted] == hashStoredBlockInfo(storedBlockInfo), "r"); // incorrect stored block info delete storedBlockHashes[blocksCommitted]; --blocksCommitted; revertedPriorityRequests += storedBlockInfo.priorityOperations; } totalBlocksCommitted = blocksCommitted; totalCommittedPriorityRequests -= revertedPriorityRequests; if (totalBlocksCommitted < totalBlocksProven) { totalBlocksProven = totalBlocksCommitted; } emit BlocksRevert(totalBlocksExecuted, blocksCommitted); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: UNLICENSED /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Config.sol"; import "./Utils.sol"; import "./NFTFactory.sol"; import "./TokenGovernance.sol"; /// @title Governance Contract /// @author Matter Labs contract Governance is Config { /// @notice Token added to Franklin net event NewToken(address indexed token, uint16 indexed tokenId); /// @notice Default nft factory has set event SetDefaultNFTFactory(address indexed factory); /// @notice NFT factory registered new creator account event NFTFactoryRegisteredCreator( uint32 indexed creatorAccountId, address indexed creatorAddress, address factoryAddress ); /// @notice Governor changed event NewGovernor(address newGovernor); /// @notice Token Governance changed event NewTokenGovernance(TokenGovernance newTokenGovernance); /// @notice Validator's status changed event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive); event TokenPausedUpdate(address indexed token, bool paused); /// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades address public networkGovernor; /// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 public totalTokens; /// @notice List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @notice List of registered tokens by address mapping(address => uint16) public tokenIds; /// @notice List of permitted validators mapping(address => bool) public validators; /// @notice Paused tokens list, deposits are impossible to create for paused tokens mapping(uint16 => bool) public pausedTokens; /// @notice Address that is authorized to add tokens to the Governance. TokenGovernance public tokenGovernance; /// @notice NFT Creator address to factory address mapping mapping(uint32 => mapping(address => NFTFactory)) public nftFactories; /// @notice Address which will be used if NFT token has no factories NFTFactory public defaultFactory; /// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _networkGovernor The address of network governor function initialize(bytes calldata initializationParameters) external { address _networkGovernor = abi.decode(initializationParameters, (address)); networkGovernor = _networkGovernor; } /// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters // solhint-disable-next-line no-empty-blocks function upgrade(bytes calldata upgradeParameters) external {} /// @notice Change current governor /// @param _newGovernor Address of the new governor function changeGovernor(address _newGovernor) external { requireGovernor(msg.sender); if (networkGovernor != _newGovernor) { networkGovernor = _newGovernor; emit NewGovernor(_newGovernor); } } /// @notice Change current token governance /// @param _newTokenGovernance Address of the new token governor function changeTokenGovernance(TokenGovernance _newTokenGovernance) external { requireGovernor(msg.sender); if (tokenGovernance != _newTokenGovernance) { tokenGovernance = _newTokenGovernance; emit NewTokenGovernance(_newTokenGovernance); } } /// @notice Add token to the list of networks tokens /// @param _token Token address function addToken(address _token) external { require(msg.sender == address(tokenGovernance), "1E"); require(tokenIds[_token] == 0, "1e"); // token exists require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens totalTokens++; uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth tokenAddresses[newTokenId] = _token; tokenIds[_token] = newTokenId; emit NewToken(_token, newTokenId); } /// @notice Pause token deposits for the given token /// @param _tokenAddr Token address /// @param _tokenPaused Token paused status function setTokenPaused(address _tokenAddr, bool _tokenPaused) external { requireGovernor(msg.sender); uint16 tokenId = this.validateTokenAddress(_tokenAddr); if (pausedTokens[tokenId] != _tokenPaused) { pausedTokens[tokenId] = _tokenPaused; emit TokenPausedUpdate(_tokenAddr, _tokenPaused); } } /// @notice Change validator status (active or not active) /// @param _validator Validator address /// @param _active Active flag function setValidator(address _validator, bool _active) external { requireGovernor(msg.sender); if (validators[_validator] != _active) { validators[_validator] = _active; emit ValidatorStatusUpdate(_validator, _active); } } /// @notice Check if specified address is is governor /// @param _address Address to check function requireGovernor(address _address) public view { require(_address == networkGovernor, "1g"); // only by governor } /// @notice Checks if validator is active /// @param _address Validator address function requireActiveValidator(address _address) external view { require(validators[_address], "1h"); // validator is not active } /// @notice Validate token id (must be less than or equal to total tokens amount) /// @param _tokenId Token id /// @return bool flag that indicates if token id is less than or equal to total tokens amount function isValidTokenId(uint16 _tokenId) external view returns (bool) { return _tokenId <= totalTokens; } /// @notice Validate token address /// @param _tokenAddr Token address /// @return tokens id function validateTokenAddress(address _tokenAddr) external view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "1i"); // 0 is not a valid token return tokenId; } function packRegisterNFTFactoryMsg( uint32 _creatorAccountId, address _creatorAddress, address _factoryAddress ) internal pure returns (bytes memory) { return abi.encodePacked( "\x19Ethereum Signed Message:\n141", "\nCreator's account ID in zkSync: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAccountId))), "\nCreator: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAddress))), "\nFactory: ", Bytes.bytesToHexASCIIBytes(abi.encodePacked((_factoryAddress))) ); } /// @notice Register creator corresponding to the factory /// @param _creatorAccountId Creator's zkSync account ID /// @param _creatorAddress NFT creator address /// @param _signature Creator's signature function registerNFTFactoryCreator( uint32 _creatorAccountId, address _creatorAddress, bytes memory _signature ) external { require(address(nftFactories[_creatorAccountId][_creatorAddress]) == address(0), "Q"); bytes32 messageHash = keccak256(packRegisterNFTFactoryMsg(_creatorAccountId, _creatorAddress, msg.sender)); address recoveredAddress = Utils.recoverAddressFromEthSignature(_signature, messageHash); require(recoveredAddress == _creatorAddress && recoveredAddress != address(0), "ws"); nftFactories[_creatorAccountId][_creatorAddress] = NFTFactory(msg.sender); emit NFTFactoryRegisteredCreator(_creatorAccountId, _creatorAddress, msg.sender); } //@notice Set default factory for our contract. This factory will be used to mint an NFT token that has no factory //@param _factory Address of NFT factory function setDefaultNFTFactory(address _factory) external { requireGovernor(msg.sender); require(address(_factory) != address(0), "mb1"); // Factory should be non zero require(address(defaultFactory) == address(0), "mb2"); // NFTFactory is already set defaultFactory = NFTFactory(_factory); emit SetDefaultNFTFactory(_factory); } function getNFTFactory(uint32 _creatorAccountId, address _creatorAddress) external view returns (NFTFactory) { NFTFactory _factory = nftFactories[_creatorAccountId][_creatorAddress]; if (address(_factory) == address(0)) { require(address(defaultFactory) != address(0), "fs"); // NFTFactory does not set return defaultFactory; } else { return _factory; } } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./KeysWithPlonkVerifier.sol"; import "./Config.sol"; // Hardcoded constants to avoid accessing store contract Verifier is KeysWithPlonkVerifier, KeysWithPlonkVerifierOld, Config { // solhint-disable-next-line no-empty-blocks function initialize(bytes calldata) external {} /// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters // solhint-disable-next-line no-empty-blocks function upgrade(bytes calldata upgradeParameters) external {} function verifyAggregatedBlockProof( uint256[] memory _recursiveInput, uint256[] memory _proof, uint8[] memory _vkIndexes, uint256[] memory _individualVksInputs, uint256[16] memory _subproofsLimbs ) external view returns (bool) { for (uint256 i = 0; i < _individualVksInputs.length; ++i) { uint256 commitment = _individualVksInputs[i]; _individualVksInputs[i] = commitment & INPUT_MASK; } VerificationKey memory vk = getVkAggregated(uint32(_vkIndexes.length)); return verify_serialized_proof_with_recursion( _recursiveInput, _proof, VK_TREE_ROOT, VK_MAX_INDEX, _vkIndexes, _individualVksInputs, _subproofsLimbs, vk ); } function verifyExitProof( bytes32 _rootHash, uint32 _accountId, address _owner, uint32 _tokenId, uint128 _amount, uint32 _nftCreatorAccountId, address _nftCreatorAddress, uint32 _nftSerialId, bytes32 _nftContentHash, uint256[] calldata _proof ) external view returns (bool) { bytes32 commitment = sha256( abi.encodePacked( _rootHash, _accountId, _owner, _tokenId, _amount, _nftCreatorAccountId, _nftCreatorAddress, _nftSerialId, _nftContentHash ) ); uint256[] memory inputs = new uint256[](1); inputs[0] = uint256(commitment) & INPUT_MASK; ProofOld memory proof = deserialize_proof_old(inputs, _proof); VerificationKeyOld memory vk = getVkExit(); require(vk.num_inputs == inputs.length, "n1"); return verify_old(proof, vk); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: UNLICENSED interface NFTFactory { function mintNFTFromZkSync( address creator, address recipient, uint32 creatorAccountId, uint32 serialId, bytes32 contentHash, // Even though the token id can fit into the uint32, we still use // the uint256 to preserve consistency with the ERC721 parent contract uint256 tokenId ) external; event MintNFTFromZkSync( address indexed creator, address indexed recipient, uint32 creatorAccountId, uint32 serialId, bytes32 contentHash, uint256 tokenId ); } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./Governance.sol"; import "./IERC20.sol"; import "./Utils.sol"; /// @title Token Governance Contract /// @author Matter Labs /// @notice Contract is used to allow anyone to add new ERC20 tokens to zkSync given sufficient payment contract TokenGovernance { /// @notice Token lister added or removed (see `tokenLister`) event TokenListerUpdate(address indexed tokenLister, bool isActive); /// @notice Listing fee token set event ListingFeeTokenUpdate(IERC20 indexed newListingFeeToken); /// @notice Listing fee set event ListingFeeUpdate(uint256 newListingFee); /// @notice Maximum number of listed tokens updated event ListingCapUpdate(uint16 newListingCap); /// @notice The treasury (the account which will receive the fee) was updated event TreasuryUpdate(address newTreasury); /// @notice zkSync governance contract Governance public governance; /// @notice Token used to collect listing fee for addition of new token to zkSync network IERC20 public listingFeeToken; /// @notice Token listing fee uint256 public listingFee; /// @notice Max number of tokens that can be listed using this contract uint16 public listingCap; /// @notice Addresses that can list tokens without fee mapping(address => bool) public tokenLister; /// @notice Address that collects listing payments address public treasury; constructor( Governance _governance, IERC20 _listingFeeToken, uint256 _listingFee, uint16 _listingCap, address _treasury ) { governance = _governance; listingFeeToken = _listingFeeToken; listingFee = _listingFee; listingCap = _listingCap; treasury = _treasury; address governor = governance.networkGovernor(); // We add zkSync governor as a first token lister. tokenLister[governor] = true; emit TokenListerUpdate(governor, true); } /// @notice Adds new ERC20 token to zkSync network. /// @notice If caller is not present in the `tokenLister` map payment of `listingFee` in `listingFeeToken` should be made. /// @notice NOTE: before calling this function make sure to approve `listingFeeToken` transfer for this contract. function addToken(address _token) external { require(governance.totalTokens() < listingCap, "can't add more tokens"); // Impossible to add more tokens using this contract if (!tokenLister[msg.sender]) { // Collect fees bool feeTransferOk = Utils.transferFromERC20(listingFeeToken, msg.sender, treasury, listingFee); require(feeTransferOk, "fee transfer failed"); // Failed to receive payment for token addition. } governance.addToken(_token); } /// Governance functions (this contract is governed by zkSync governor) /// @notice Set new listing token and fee /// @notice Can be called only by zkSync governor function setListingFeeToken(IERC20 _newListingFeeToken, uint256 _newListingFee) external { governance.requireGovernor(msg.sender); listingFeeToken = _newListingFeeToken; listingFee = _newListingFee; emit ListingFeeTokenUpdate(_newListingFeeToken); } /// @notice Set new listing fee /// @notice Can be called only by zkSync governor function setListingFee(uint256 _newListingFee) external { governance.requireGovernor(msg.sender); listingFee = _newListingFee; emit ListingFeeUpdate(_newListingFee); } /// @notice Enable or disable token lister. If enabled new tokens can be added by that address without payment /// @notice Can be called only by zkSync governor function setLister(address _listerAddress, bool _active) external { governance.requireGovernor(msg.sender); if (tokenLister[_listerAddress] != _active) { tokenLister[_listerAddress] = _active; emit TokenListerUpdate(_listerAddress, _active); } } /// @notice Change maximum amount of tokens that can be listed using this method /// @notice Can be called only by zkSync governor function setListingCap(uint16 _newListingCap) external { governance.requireGovernor(msg.sender); listingCap = _newListingCap; emit ListingCapUpdate(_newListingCap); } /// @notice Change address that collects payments for listing tokens. /// @notice Can be called only by zkSync governor function setTreasury(address _newTreasury) external { governance.requireGovernor(msg.sender); treasury = _newTreasury; emit TreasuryUpdate(_newTreasury); } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 import "./PlonkCore.sol"; // Hardcoded constants to avoid accessing store contract KeysWithPlonkVerifier is VerifierWithDeserialize { uint256 constant VK_TREE_ROOT = 0x12d3ca8e7e185734779f3969f1d0a9dbb357a737ed605c37c7157c341012e6d9; uint8 constant VK_MAX_INDEX = 3; function getVkAggregated(uint32 _proofs) internal pure returns (VerificationKey memory vk) { if (_proofs == uint32(1)) { return getVkAggregated1(); } else if (_proofs == uint32(4)) { return getVkAggregated4(); } else if (_proofs == uint32(8)) { return getVkAggregated8(); } } function getVkAggregated1() internal pure returns(VerificationKey memory vk) { vk.domain_size = 4194304; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b, 0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48 ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e, 0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0 ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5, 0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123 ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7, 0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346 ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263, 0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474, 0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927, 0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c, 0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951, 0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3, 0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6, 0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899, 0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1, 0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59 ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkAggregated4() internal pure returns(VerificationKey memory vk) { vk.domain_size = 8388608; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x1283ba6f4b7b1a76ba2008fe823128bea4adb9269cbfd7c41c223be65bc60863); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x2988e24b15bce9a1e3a4d1d9a8f7c7a65db6c29fd4c6f4afe1a3fbd954d4b4b6, 0x0bdb6e5ba27a22e03270c7c71399b866b28d7cec504d30e665d67be58e306e12 ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x20f3d30d3a91a7419d658f8c035e42a811c9f75eac2617e65729033286d36089, 0x07ac91e8194eb78a9db537e9459dd6ca26bef8770dde54ac3dd396450b1d4cfe ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x0311872bab6df6e9095a9afe40b12e2ed58f00cc88835442e6b4cf73fb3e147d, 0x2cdfc5b5e73737809b54644b2f96494f8fcc1dd0fb440f64f44930b432c4542d ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x28fd545b1e960d2eff3142271affa4096ef724212031fdabe22dd4738f36472b, 0x2c743150ee9894ff3965d8f1129399a3b89a1a9289d4cfa904b0a648d3a8a9fa ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x2c283ce950eee1173b78657e57c80658a8398e7970a9a45b20cd39aff16ad61a, 0x081c003cbd09f7c3e0d723d6ebbaf432421c188d5759f5ee8ff1ee1dc357d4a8 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x2eb50a2dd293a71a0c038e958c5237bd7f50b2f0c9ee6385895a553de1517d43, 0x15fdc2b5b28fc351f987b98aa6caec7552cefbafa14e6651061eec4f41993b65 ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x17a9403e5c846c1ca5e767c89250113aa156fdb1f026aa0b4db59c09d06816ec, 0x2512241972ca3ee4839ac72a4cab39ddb413a7553556abd7909284b34ee73f6b ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x09edd69c8baa7928b16615e993e3032bc8cbf9f42bfa3cf28caba1078d371edb, 0x12e5c39148af860a87b14ae938f33eafa91deeb548cda4cc23ed9ba3e6e496b8 ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x0e25c0027706ca3fd3daae849f7c50ec88d4d030da02452001dec7b554cc71b4, 0x2421da0ca385ff7ba9e5ae68890655669248c8c8187e67d12b2a7ae97e2cff8b ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x151536359fe184567bce57379833f6fae485e5cc9bc27423d83d281aaf2701df, 0x116beb145bc27faae5a8ae30c28040d3baafb3ea47360e528227b94adb9e4f26 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x23ee338093db23364a6e44acfb60d810a4c4bd6565b185374f7840152d3ae82c, 0x0f6714f3ee113b9dfb6b653f04bf497602588b16b96ac682d9a5dd880a0aa601 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x05860b0ea3c6f22150812aee304bf35e1a95cfa569a8da52b42dba44a122378a, 0x19e5a9f3097289272e65e842968752c5355d1cdb2d3d737050e4dfe32ebe1e41 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x3046881fcbe369ac6f99fea8b9505de85ded3de3bc445060be4bc6ef651fa352, 0x06fe14c1dd6c2f2b48aebeb6fd525573d276b2e148ad25e75c57a58588f755ec ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkAggregated8() internal pure returns(VerificationKey memory vk) { vk.domain_size = 16777216; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x218bdb295b7207114aeea948e2d3baef158d4057812f94005d8ff54341b6ce6f, 0x1398585c039ba3cf336687301e95fbbf6b0638d31c64b1d815bb49091d0c1aad ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x2e40b8a98e688c9e00f607a64520a850d35f277dc0b645628494337bb75870e8, 0x2da4ef753cc4869e53cff171009dbffea9166b8ffbafd17783d712278a79f13e ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x1b638de3c6cc2e0badc48305ee3533678a45f52edf30277303551128772303a2, 0x2794c375cbebb7c28379e8abf42d529a1c291319020099935550c83796ba14ac ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x189cd01d67b44cf2c1e10765c69adaafd6a5929952cf55732e312ecf00166956, 0x15976c99ef2c911bd3a72c9613b7fe9e66b03dd8963bfed705c96e3e88fdb1af ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x0745a77052dc66afc61163ec3737651e5b846ca7ec7fae1853515d0f10a51bd9, 0x2bd27ecf4fb7f5053cc6de3ddb7a969fac5150a6fb5555ca917d16a7836e4c0a ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x2787aea173d07508083893b02ea962be71c3b628d1da7d7c4db0def49f73ad8f, 0x22fdc951a97dc2ac7d8292a6c263898022f4623c643a56b9265b33c72e628886 ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x0aafe35c49634858e44e9af259cac47a6f8402eb870f9f95217dcb8a33a73e64, 0x1b47a7641a7c918784e84fc2494bfd8014ebc77069b94650d25cb5e25fbb7003 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x11cfc3fe28dfd5d663d53ceacc5ec620da85ae5aa971f0f003f57e75cd05bf9f, 0x28b325f30984634fc46c6750f402026d4ff43e5325cbe34d35bf8ac4fc9cc533 ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x2ada816636b9447def36e35dd3ab0e3f7a8bbe3ae32a5a4904dee3fc26e58015, 0x2cd12d1a50aaadef4e19e1b1955c932e992e688c2883da862bd7fad17aae66f6 ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x20cc506f273be4d114cbf2807c14a769d03169168892e2855cdfa78c3095c89d, 0x08f99d338aee985d780d036473c624de9fd7960b2a4a7ad361c8c125cf11899e ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x01260265d3b1167eac1030f3d04326f08a1f2bb1e026e54afec844e3729386e2, 0x16d75b53ec2552c63e84ea5f4bfe1507c3198045875457c1d9295d6699f39d56 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x1f4d73c63d163c3f5ef1b5caa41988cacbdbca38334e8f54d7ee9bbbb622e200, 0x2f48f5f93d9845526ef0348f1c3def63cfc009645eb2a95d1746c7941e888a78 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x1dbd386fe258366222becc570a7f6405b25ff52818b93bdd54eaa20a6b22025a, 0x2b2b4e978ac457d752f50b02609bd7d2054286b963821b2ec7cd3dd1507479fa ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } // Hardcoded constants to avoid accessing store contract KeysWithPlonkVerifierOld is VerifierWithDeserializeOld { function getVkExit() internal pure returns(VerificationKeyOld memory vk) { vk.domain_size = 524288; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x0cf1526aaafac6bacbb67d11a4077806b123f767e4b0883d14cc0193568fc082); vk.selector_commitments[0] = PairingsBn254.new_g1( 0x114dd473f77a15b602201577dd4b64a32a783cb32fbc02911e512df6a219695d, 0x04c68f82a5dd7d0cc90318bdff493b3d552d148ad859c373ffe55275e043c43b ); vk.selector_commitments[1] = PairingsBn254.new_g1( 0x245e8c882af503cb5421f5135b4295a920ccf68b42ae7fb967f044f54e2aaa29, 0x071322ee387a9ce49fe7ef2edb6e9237203dee49ec47483af85e356b79fb06fd ); vk.selector_commitments[2] = PairingsBn254.new_g1( 0x0187754ab593b07a420b3b4d215c20ed49acf90fc4c97e4b06e8f5bc0a2eb3f4, 0x0170f9286ce950286a16ea25136c163c0b32019f31b89c256a612d40b863d0b6 ); vk.selector_commitments[3] = PairingsBn254.new_g1( 0x0defecfae1d2b9ec9b2ee4d4798c625fa50f6a4ddb7747a7293df0c17fcb90c2, 0x0f91d08fceebf85fb80f12cda78cefa1ee9dbf5cfe7c4f0704b3c6620fa50c55 ); vk.selector_commitments[4] = PairingsBn254.new_g1( 0x2f7fef3b3fb64af6640f93803a18b3e5ce4e0e60aecd4f924c833fa6fa6da961, 0x03908fc737113ac7f3529fe3b36efca200c66d1d85d2fc081973214c586de732 ); vk.selector_commitments[5] = PairingsBn254.new_g1( 0x14ce3c0e9b78fc331327249e707f58fa4bb0ed746bdc9c2262ad0cf905609627, 0x09e64fdac452b424e98fc4a92f7222693d0d84ab48aadd9c46151dbe5f1a34a9 ); // we only have access to value of the d(x) witness polynomial on the next // trace step, so we only need one element here and deal with it in other places // by having this in mind vk.next_step_selector_commitments[0] = PairingsBn254.new_g1( 0x1d10bfd923c17d9623ec02db00099355b373021432ae1edef69b0f5f461f78d6, 0x24e370a93f65f42888781d0158bb6ef9136c8bbd047d7993b8276bc8df8b640a ); vk.permutation_commitments[0] = PairingsBn254.new_g1( 0x1fd1755ed4d06d91d50db4771d332cfa2bc2ca0e10ac8b77e0d6b73b993e788e, 0x0bdbf3b7f0d3cffdcf818f1fba18b90914eda59b454bd1858c6c0916b817f883 ); vk.permutation_commitments[1] = PairingsBn254.new_g1( 0x1f3b8d12ffa2ceb2bb42d232ad2cf11bce3183472b622e11cc841d26f42ad507, 0x0ce815e32b3bd14311cde210cda1bd351617d539ed3e9d96a8605f364f3a29b0 ); vk.permutation_commitments[2] = PairingsBn254.new_g1( 0x123afa8c1cec1956d7330db062498a2a3e3a9862926c02e1228d9cfb63d3c301, 0x0f5af15ff0a3e35486c541f72956b53ff6d0740384ef6463c866146c1bd2afc8 ); vk.permutation_commitments[3] = PairingsBn254.new_g1( 0x01069e38ea6396af1623921101d3d3d14ee46942fb23bf1d110efb994c3ee573, 0x232a8ce7151e69601a7867f9dcac8e2de4dd8352d119c90bbb0fb84720c02513 ); vk.permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } pragma solidity >=0.5.0 <0.8.0; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT OR Apache-2.0 // solhint-disable library PairingsBn254 { uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant bn254_b_coeff = 3; struct G1Point { uint256 X; uint256 Y; } struct Fr { uint256 value; } function new_fr(uint256 fr) internal pure returns (Fr memory) { require(fr < r_mod); return Fr({value: fr}); } function copy(Fr memory self) internal pure returns (Fr memory n) { n.value = self.value; } function assign(Fr memory self, Fr memory other) internal pure { self.value = other.value; } function inverse(Fr memory fr) internal view returns (Fr memory) { require(fr.value != 0); return pow(fr, r_mod - 2); } function add_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, other.value, r_mod); } function sub_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, r_mod - other.value, r_mod); } function mul_assign(Fr memory self, Fr memory other) internal pure { self.value = mulmod(self.value, other.value, r_mod); } function pow(Fr memory self, uint256 power) internal view returns (Fr memory) { uint256[6] memory input = [32, 32, 32, self.value, power, r_mod]; uint256[1] memory result; bool success; assembly { success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20) } require(success); return Fr({value: result[0]}); } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint256[2] X; uint256[2] Y; } function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); } function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) { return G1Point(x, y); } function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) { if (x == 0 && y == 0) { // point of infinity is (0,0) return G1Point(x, y); } // check encoding require(x < q_mod); require(y < q_mod); // check on curve uint256 lhs = mulmod(y, y, q_mod); // y^2 uint256 rhs = mulmod(x, x, q_mod); // x^2 rhs = mulmod(rhs, x, q_mod); // x^3 rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b require(lhs == rhs); return G1Point(x, y); } function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) { return G2Point(x, y); } function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) { result.X = self.X; result.Y = self.Y; } function P2() internal pure returns (G2Point memory) { // for some reason ethereum expects to have c1*v + c0 form return G2Point( [ 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed ], [ 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa ] ); } function negate(G1Point memory self) internal pure { // The prime q in the base field F_q for G1 if (self.Y == 0) { require(self.X == 0); return; } self.Y = q_mod - self.Y; } function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { point_add_into_dest(p1, p2, r); return r; } function point_add_assign(G1Point memory p1, G1Point memory p2) internal view { point_add_into_dest(p1, p2, p1); } function point_add_into_dest( G1Point memory p1, G1Point memory p2, G1Point memory dest ) internal view { if (p2.X == 0 && p2.Y == 0) { // we add zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we add into zero, and we add non-zero point dest.X = p2.X; dest.Y = p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view { point_sub_into_dest(p1, p2, p1); } function point_sub_into_dest( G1Point memory p1, G1Point memory p2, G1Point memory dest ) internal view { if (p2.X == 0 && p2.Y == 0) { // we subtracted zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we subtract from zero, and we subtract non-zero point dest.X = p2.X; dest.Y = q_mod - p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = q_mod - p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) { point_mul_into_dest(p, s, r); return r; } function point_mul_assign(G1Point memory p, Fr memory s) internal view { point_mul_into_dest(p, s, p); } function point_mul_into_dest( G1Point memory p, Fr memory s, G1Point memory dest ) internal view { uint256[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s.value; bool success; assembly { success := staticcall(gas(), 7, input, 0x60, dest, 0x40) } require(success); } function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length); uint256 elements = p1.length; uint256 inputSize = elements * 6; uint256[] memory input = new uint256[](inputSize); for (uint256 i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint256[1] memory out; bool success; assembly { success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } } library TranscriptLibrary { // flip 0xe000000000000000000000000000000000000000000000000000000000000000; uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint32 constant DST_0 = 0; uint32 constant DST_1 = 1; uint32 constant DST_CHALLENGE = 2; struct Transcript { bytes32 state_0; bytes32 state_1; uint32 challenge_counter; } function new_transcript() internal pure returns (Transcript memory t) { t.state_0 = bytes32(0); t.state_1 = bytes32(0); t.challenge_counter = 0; } function update_with_u256(Transcript memory self, uint256 value) internal pure { bytes32 old_state_0 = self.state_0; self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value)); self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value)); } function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure { update_with_u256(self, value.value); } function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure { update_with_u256(self, p.X); update_with_u256(self, p.Y); } function get_challenge(Transcript memory self) internal pure returns (PairingsBn254.Fr memory challenge) { bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter)); self.challenge_counter += 1; challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK}); } } contract Plonk4VerifierWithAccessToDNext { uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant ZERO = 0; uint256 constant ONE = 1; uint256 constant TWO = 2; uint256 constant THREE = 3; uint256 constant FOUR = 4; uint256 constant STATE_WIDTH = 4; uint256 constant NUM_DIFFERENT_GATES = 2; uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7; uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1; uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1; uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant LIMB_WIDTH = 68; struct VerificationKey { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments; PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments; PairingsBn254.Fr[STATE_WIDTH - 1] copy_permutation_non_residues; PairingsBn254.G2Point g2_x; } struct Proof { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH] wire_commitments; PairingsBn254.G1Point copy_permutation_grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega; PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z; PairingsBn254.Fr copy_grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH - 1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierState { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function batch_evaluate_lagrange_poly_out_of_domain( uint256[] memory poly_nums, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr[] memory res) { PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size); PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size); vanishing_at_z.sub_assign(one); // we can not have random point z be in domain require(vanishing_at_z.value != 0); PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length); PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length); // numerators in a form omega^i * (z^n - 1) // denoms in a form (z - omega^i) * N for (uint256 i = 0; i < poly_nums.length; i++) { tmp_1 = omega.pow(poly_nums[i]); // power of omega nums[i].assign(vanishing_at_z); nums[i].mul_assign(tmp_1); dens[i].assign(at); // (X - omega^i) * N dens[i].sub_assign(tmp_1); dens[i].mul_assign(tmp_2); // mul by domain size } PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length); partial_products[0].assign(PairingsBn254.new_fr(1)); for (uint256 i = 1; i < dens.length - 1; i++) { partial_products[i].assign(dens[i - 1]); partial_products[i].mul_assign(dens[i]); } tmp_2.assign(partial_products[partial_products.length - 1]); tmp_2.mul_assign(dens[dens.length - 1]); tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one) for (uint256 i = dens.length - 1; i < dens.length; i--) { dens[i].assign(tmp_2); // all inversed dens[i].mul_assign(partial_products[i]); // clear lowest terms tmp_2.mul_assign(dens[i]); } for (uint256 i = 0; i < nums.length; i++) { nums[i].mul_assign(dens[i]); } return nums; } function evaluate_vanishing(uint256 domain_size, PairingsBn254.Fr memory at) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); inputs_term.add_assign(tmp); } inputs_term.mul_assign(proof.gate_selector_values_at_z[0]); rhs.add_assign(inputs_term); // now we need 5th power quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function add_contribution_from_range_constraint_gates( PartialVerifierState memory state, Proof memory proof, PairingsBn254.Fr memory current_alpha ) internal pure returns (PairingsBn254.Fr memory res) { // now add contribution from range constraint gate // we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {}) PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE); PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO); PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE); PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR); res = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0); for (uint256 i = 0; i < 3; i++) { current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); } // now also d_next - 4a current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[0]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); return res; } function reconstruct_linearization_commitment( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^{6} * (selector(x) - selector(z)) // + v^{7..9} * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^10 (z(x) - z(z*omega)) <- we need this power // + v^11 * (d(x) - d(z*omega)) // ] // // we reconstruct linearization polynomial virtual selector // for that purpose we first linearize over main gate (over all it's selectors) // and multiply them by value(!) of the corresponding main gate selector res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x) PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH; i++) { tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH + 2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x) res.point_add_assign(tmp_g1); // multiply by main gate selector(z) res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE); // calculate scalar contribution from the range check gate tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha); tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar res.point_add_assign(tmp_g1); // proceed as normal to copy permutation current_alpha.mul_assign(state.alpha); // alpha^5 PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i + 1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(alpha_for_grand_product); // alpha^n & L_{0}(z), and we bump current_alpha current_alpha.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(current_alpha); grand_product_part_at_z.add_assign(tmp_fr); // prefactor for grand_product(x) is complete // add to the linearization a part from the term // - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X) PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument // actually multiply prefactors by z(x) and perm_d(x) and combine them tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); // multiply them by v immedately as linearization has a factor of v^1 res.point_mul_assign(state.v); // res now contains contribution from the gates linearization and // copy permutation part // now we need to add a part that is the rest // for z(x*omega): // - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega) } function aggregate_commitments( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point[2] memory res) { PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint256 i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint256 i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.gate_selector_commitments[0].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint256 i = 0; i < vk.copy_permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); // now do prefactor for grand_product(x*omega) tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr)); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.gate_selector_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.copy_grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); res[0] = pair_with_generator; res[1] = pair_with_x; return res; } function verify_initial( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs >= 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.copy_permutation_grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs); for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) { lagrange_poly_numbers[i] = i; } state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain( lagrange_poly_numbers, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } transcript.update_with_fr(proof.quotient_polynomial_at_z); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } transcript.update_with_fr(proof.gate_selector_values_at_z[0]); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.copy_grand_product_at_z_omega); transcript.update_with_fr(proof.linearization_polynomial_at_z); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function aggregate_for_verification(Proof memory proof, VerificationKey memory vk) internal view returns (bool valid, PairingsBn254.G1Point[2] memory part) { PartialVerifierState memory state; valid = verify_initial(state, proof, vk); if (valid == false) { return (valid, part); } part = aggregate_commitments(state, proof, vk); (valid, part); } function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) { (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } valid = PairingsBn254.pairingProd2( recursive_proof_part[0], PairingsBn254.P2(), recursive_proof_part[1], vk.g2_x ); return valid; } function verify_recursive( Proof memory proof, VerificationKey memory vk, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[16] memory subproofs_limbs ) internal view returns (bool) { (uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) = reconstruct_recursive_public_input( recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs ); assert(recursive_input == proof.input_values[0]); (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } // aggregated_g1s = inner // recursive_proof_part = outer PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part); valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x); return valid; } function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer) internal view returns (PairingsBn254.G1Point[2] memory result) { // reuse the transcript primitive TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); transcript.update_with_g1(inner[0]); transcript.update_with_g1(inner[1]); transcript.update_with_g1(outer[0]); transcript.update_with_g1(outer[1]); PairingsBn254.Fr memory challenge = transcript.get_challenge(); // 1 * inner + challenge * outer result[0] = PairingsBn254.copy_g1(inner[0]); result[1] = PairingsBn254.copy_g1(inner[1]); PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge); result[0].point_add_assign(tmp); tmp = outer[1].point_mul(challenge); result[1].point_add_assign(tmp); return result; } function reconstruct_recursive_public_input( uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[16] memory subproofs_aggregated ) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) { assert(recursive_vks_indexes.length == individual_vks_inputs.length); bytes memory concatenated = abi.encodePacked(recursive_vks_root); uint8 index; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { index = recursive_vks_indexes[i]; assert(index <= max_valid_index); concatenated = abi.encodePacked(concatenated, index); } uint256 input; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { input = individual_vks_inputs[i]; assert(input < r_mod); concatenated = abi.encodePacked(concatenated, input); } concatenated = abi.encodePacked(concatenated, subproofs_aggregated); bytes32 commitment = sha256(concatenated); recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK; reconstructed_g1s[0] = PairingsBn254.new_g1_checked( subproofs_aggregated[0] + (subproofs_aggregated[1] << LIMB_WIDTH) + (subproofs_aggregated[2] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[3] << (3 * LIMB_WIDTH)), subproofs_aggregated[4] + (subproofs_aggregated[5] << LIMB_WIDTH) + (subproofs_aggregated[6] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[7] << (3 * LIMB_WIDTH)) ); reconstructed_g1s[1] = PairingsBn254.new_g1_checked( subproofs_aggregated[8] + (subproofs_aggregated[9] << LIMB_WIDTH) + (subproofs_aggregated[10] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[11] << (3 * LIMB_WIDTH)), subproofs_aggregated[12] + (subproofs_aggregated[13] << LIMB_WIDTH) + (subproofs_aggregated[14] << (2 * LIMB_WIDTH)) + (subproofs_aggregated[15] << (3 * LIMB_WIDTH)) ); return (recursive_input, reconstructed_g1s); } } contract VerifierWithDeserialize is Plonk4VerifierWithAccessToDNext { uint256 constant SERIALIZED_PROOF_LENGTH = 34; function deserialize_proof(uint256[] memory public_inputs, uint256[] memory serialized_proof) internal pure returns (Proof memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; } proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j + 1] ); j += 2; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j + 1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) { proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); } function verify_serialized_proof( uint256[] memory public_inputs, uint256[] memory serialized_proof, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify(proof, vk); return valid; } function verify_serialized_proof_with_recursion( uint256[] memory public_inputs, uint256[] memory serialized_proof, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[16] memory subproofs_limbs, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify_recursive( proof, vk, recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs ); return valid; } } contract Plonk4VerifierWithAccessToDNextOld { using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant STATE_WIDTH_OLD = 4; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD = 1; struct VerificationKeyOld { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[STATE_WIDTH_OLD + 2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] next_step_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH_OLD] permutation_commitments; PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_non_residues; PairingsBn254.G2Point g2_x; } struct ProofOld { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH_OLD] wire_commitments; PairingsBn254.G1Point grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH_OLD] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH_OLD] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] wire_values_at_z_omega; PairingsBn254.Fr grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierStateOld { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain_old( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function batch_evaluate_lagrange_poly_out_of_domain_old( uint256[] memory poly_nums, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr[] memory res) { PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size); PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size); vanishing_at_z.sub_assign(one); // we can not have random point z be in domain require(vanishing_at_z.value != 0); PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length); PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length); // numerators in a form omega^i * (z^n - 1) // denoms in a form (z - omega^i) * N for (uint256 i = 0; i < poly_nums.length; i++) { tmp_1 = omega.pow(poly_nums[i]); // power of omega nums[i].assign(vanishing_at_z); nums[i].mul_assign(tmp_1); dens[i].assign(at); // (X - omega^i) * N dens[i].sub_assign(tmp_1); dens[i].mul_assign(tmp_2); // mul by domain size } PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length); partial_products[0].assign(PairingsBn254.new_fr(1)); for (uint256 i = 1; i < dens.length - 1; i++) { partial_products[i].assign(dens[i - 1]); partial_products[i].mul_assign(dens[i]); } tmp_2.assign(partial_products[partial_products.length - 1]); tmp_2.mul_assign(dens[dens.length - 1]); tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one) for (uint256 i = dens.length - 1; i < dens.length; i--) { dens[i].assign(tmp_2); // all inversed dens[i].mul_assign(partial_products[i]); // clear lowest terms tmp_2.mul_assign(dens[i]); } for (uint256 i = 0; i < nums.length; i++) { nums[i].mul_assign(dens[i]); } return nums; } function evaluate_vanishing_old(uint256 domain_size, PairingsBn254.Fr memory at) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing_old(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); rhs.add_assign(tmp); } quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH_OLD - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function reconstruct_d( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^(6..8) * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^9 (z(x) - z(z*omega)) <- we need this power // + v^10 * (d(x) - d(z*omega)) // ] // // we pay a little for a few arithmetic operations to not introduce another constant uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH_OLD + STATE_WIDTH_OLD - 1; res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH_OLD + 1]); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.selector_commitments[STATE_WIDTH_OLD].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]); res.point_add_assign(tmp_g1); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i + 1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(state.alpha); tmp_fr.mul_assign(state.alpha); grand_product_part_at_z.add_assign(tmp_fr); PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening); grand_product_part_at_z_omega.mul_assign(state.u); PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(state.alpha); // add to the linearization tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH_OLD - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); res.point_mul_assign(state.v); res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega)); } function verify_commitments( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (bool) { PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint256 i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint256 i = 0; i < vk.permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH_OLD - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x); } function verify_initial( PartialVerifierStateOld memory state, ProofOld memory proof, VerificationKeyOld memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs >= 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs); for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) { lagrange_poly_numbers[i] = i; } state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain_old( lagrange_poly_numbers, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.quotient_polynomial_at_z); transcript.update_with_fr(proof.linearization_polynomial_at_z); transcript.update_with_fr(proof.grand_product_at_z_omega); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function verify_old(ProofOld memory proof, VerificationKeyOld memory vk) internal view returns (bool) { PartialVerifierStateOld memory state; bool valid = verify_initial(state, proof, vk); if (valid == false) { return false; } valid = verify_commitments(state, proof, vk); return valid; } } contract VerifierWithDeserializeOld is Plonk4VerifierWithAccessToDNextOld { uint256 constant SERIALIZED_PROOF_LENGTH_OLD = 33; function deserialize_proof_old(uint256[] memory public_inputs, uint256[] memory serialized_proof) internal pure returns (ProofOld memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH_OLD); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; } proof.grand_product_commitment = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j + 1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } proof.grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]); j += 1; for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]); j += 1; } proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]); } } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title Interface of the upgradeable contract /// @author Matter Labs interface Upgradeable { /// @notice Upgrades target of upgradeable contract /// @param newTarget New target /// @param newTargetInitializationParameters New target initialization parameters function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external; } pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT OR Apache-2.0 /// @title Ownable Contract /// @author Matter Labs contract Ownable { /// @dev Storage position of the masters address (keccak256('eip1967.proxy.admin') - 1) bytes32 private constant MASTER_POSITION = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /// @notice Contract constructor /// @dev Sets msg sender address as masters address /// @param masterAddress Master address constructor(address masterAddress) { setMaster(masterAddress); } /// @notice Check if specified address is master /// @param _address Address to check function requireMaster(address _address) internal view { require(_address == getMaster(), "1c"); // oro11 - only by master } /// @notice Returns contract masters address /// @return master Master's address function getMaster() public view returns (address master) { bytes32 position = MASTER_POSITION; assembly { master := sload(position) } } /// @dev Sets new masters address /// @param _newMaster New master's address function setMaster(address _newMaster) internal { bytes32 position = MASTER_POSITION; assembly { sstore(position, _newMaster) } } /// @notice Transfer mastership of the contract to new master /// @param _newMaster New masters address function transferMastership(address _newMaster) external { requireMaster(msg.sender); require(_newMaster != address(0), "1d"); // otp11 - new masters address can't be zero address setMaster(_newMaster); } }
@notice Checks that signature is valid for pubkey change message, old version differs by form of the signed message. @param _ethWitness Signature (65 bytes) @param _changePk Parsed change pubkey operation
{ bytes32 messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n152", "Register zkSync pubkey:\n\n", Bytes.bytesToHexASCIIBytes(abi.encodePacked(_changePk.pubKeyHash)), "\n", "nonce: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.nonce)), "\n", "account id: 0x", Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.accountId)), "\n\n", "Only sign this message for a trusted client!" ) ); address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash); return recoveredAddress == _changePk.owner && recoveredAddress != address(0); }
10,422,904
[ 1, 4081, 716, 3372, 353, 923, 364, 15649, 2549, 883, 16, 1592, 1177, 21944, 635, 646, 434, 326, 6726, 883, 18, 225, 389, 546, 24007, 9249, 261, 9222, 1731, 13, 225, 389, 3427, 7789, 19244, 2549, 15649, 1674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 288, 203, 3639, 1731, 1578, 883, 2310, 273, 203, 5411, 417, 24410, 581, 5034, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 1548, 92, 3657, 41, 18664, 379, 16724, 2350, 5581, 82, 27655, 3113, 203, 10792, 315, 3996, 14164, 4047, 15649, 5581, 82, 64, 82, 3113, 203, 10792, 5985, 18, 3890, 774, 7037, 13756, 2160, 12, 21457, 18, 3015, 4420, 329, 24899, 3427, 7789, 18, 10174, 653, 2310, 13, 3631, 203, 10792, 1548, 82, 3113, 203, 10792, 315, 12824, 30, 374, 92, 3113, 203, 10792, 5985, 18, 3890, 774, 7037, 13756, 2160, 12, 2160, 18, 869, 2160, 1265, 14342, 1578, 24899, 3427, 7789, 18, 12824, 13, 3631, 203, 10792, 1548, 82, 3113, 203, 10792, 315, 4631, 612, 30, 374, 92, 3113, 203, 10792, 5985, 18, 3890, 774, 7037, 13756, 2160, 12, 2160, 18, 869, 2160, 1265, 14342, 1578, 24899, 3427, 7789, 18, 25701, 13, 3631, 203, 10792, 1548, 82, 64, 82, 3113, 203, 10792, 315, 3386, 1573, 333, 883, 364, 279, 13179, 1004, 4442, 203, 7734, 262, 203, 5411, 11272, 203, 3639, 1758, 24616, 1887, 273, 6091, 18, 266, 3165, 1887, 1265, 41, 451, 5374, 12, 8195, 16, 883, 2310, 1769, 203, 3639, 327, 24616, 1887, 422, 389, 3427, 7789, 18, 8443, 597, 24616, 1887, 480, 1758, 12, 20, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IGenericLender interface IGenericLender { function lenderName() external view returns (string memory); function nav() external view returns (uint256); function strategy() external view returns (address); function apr() external view returns (uint256); function weightedApr() external view returns (uint256); function withdraw(uint256 amount) external returns (uint256); function emergencyWithdraw(uint256 amount) external; function deposit() external; function withdrawAll() external returns (bool); function hasAssets() external view returns (bool); function aprAfterDeposit(uint256 amount) external view returns (uint256); function setDust(uint256 _dust) external; function sweep(address _token) external; } // Part: IUni interface IUni { function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: IWantToEth interface IWantToEth { function wantToEth(uint256 input) external view returns (uint256); function ethToWant(uint256 input) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: iearn-finance/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.2"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: Strategy.sol /******************** * * A lender optimisation strategy for any erc20 asset * https://github.com/Grandthrax/yearnV2-generic-lender-strat * v0.3.1 * * This strategy works by taking plugins designed for standard lending platforms * It automatically chooses the best yield generating platform and adjusts accordingly * The adjustment is sub optimal so there is an additional option to manually set position * ********************* */ contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 public withdrawalThreshold = 1e16; uint256 public constant SECONDSPERYEAR = 31556952; IGenericLender[] public lenders; bool public externalOracle; // default is false address public wantToEthOracle; event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) { debtThreshold = 100 * 1e18; } function clone(address _vault) external returns (address newStrategy) { newStrategy = 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) } Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper); emit Cloned(newStrategy); } function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized { withdrawalThreshold = _threshold; } function setPriceOracle(address _oracle) external onlyAuthorized { wantToEthOracle = _oracle; } function name() external view override returns (string memory) { return "StrategyLenderYieldOptimiser"; } //management functions //add lenders for the strategy to choose between // only governance to stop strategist adding dodgy lender function addLender(address a) public onlyGovernance { IGenericLender n = IGenericLender(a); require(n.strategy() == address(this), "Undocked Lender"); for (uint256 i = 0; i < lenders.length; i++) { require(a != address(lenders[i]), "Already Added"); } lenders.push(n); } //but strategist can remove for safety function safeRemoveLender(address a) public onlyAuthorized { _removeLender(a, false); } function forceRemoveLender(address a) public onlyAuthorized { _removeLender(a, true); } //force removes the lender even if it still has a balance function _removeLender(address a, bool force) internal { for (uint256 i = 0; i < lenders.length; i++) { if (a == address(lenders[i])) { bool allWithdrawn = lenders[i].withdrawAll(); if (!force) { require(allWithdrawn, "WITHDRAW FAILED"); } //put the last index here //remove last index if (i != lenders.length - 1) { lenders[i] = lenders[lenders.length - 1]; } //pop shortens array by 1 thereby deleting the last index lenders.pop(); //if balance to spend we might as well put it into the best lender if (want.balanceOf(address(this)) > 0) { adjustPosition(0); } return; } } require(false, "NOT LENDER"); } //we could make this more gas efficient but it is only used by a view function struct lendStatus { string name; uint256 assets; uint256 rate; address add; } //Returns the status of all lenders attached the strategy function lendStatuses() public view returns (lendStatus[] memory) { lendStatus[] memory statuses = new lendStatus[](lenders.length); for (uint256 i = 0; i < lenders.length; i++) { lendStatus memory s; s.name = lenders[i].lenderName(); s.add = address(lenders[i]); s.assets = lenders[i].nav(); s.rate = lenders[i].apr(); statuses[i] = s; } return statuses; } // lent assets plus loose assets function estimatedTotalAssets() public view override returns (uint256) { uint256 nav = lentTotalAssets(); nav = nav.add(want.balanceOf(address(this))); return nav; } function numLenders() public view returns (uint256) { return lenders.length; } //the weighted apr of all lenders. sum(nav * apr)/totalNav function estimatedAPR() public view returns (uint256) { uint256 bal = estimatedTotalAssets(); if (bal == 0) { return 0; } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { weightedAPR = weightedAPR.add(lenders[i].weightedApr()); } return weightedAPR.div(bal); } //Estimates the impact on APR if we add more money. It does not take into account adjusting position function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) { uint256 highestAPR = 0; uint256 aprChoice = 0; uint256 assets = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr = lenders[i].aprAfterDeposit(change); if (apr > highestAPR) { aprChoice = i; highestAPR = apr; assets = lenders[i].nav(); } } uint256 weightedAPR = highestAPR.mul(assets.add(change)); for (uint256 i = 0; i < lenders.length; i++) { if (i != aprChoice) { weightedAPR = weightedAPR.add(lenders[i].weightedApr()); } } uint256 bal = estimatedTotalAssets().add(change); return weightedAPR.div(bal); } //Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) { uint256 lowestApr = uint256(-1); uint256 aprChoice = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr = lenders[i].aprAfterDeposit(change); if (apr < lowestApr) { aprChoice = i; lowestApr = apr; } } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { if (i != aprChoice) { weightedAPR = weightedAPR.add(lenders[i].weightedApr()); } else { uint256 asset = lenders[i].nav(); if (asset < change) { //simplistic. not accurate change = asset; } weightedAPR = weightedAPR.add(lowestApr.mul(change)); } } uint256 bal = estimatedTotalAssets().add(change); return weightedAPR.div(bal); } //estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public function estimateAdjustPosition() public view returns ( uint256 _lowest, uint256 _lowestApr, uint256 _highest, uint256 _potential ) { //all loose assets are to be invested uint256 looseAssets = want.balanceOf(address(this)); // our simple algo // get the lowest apr strat // cycle through and see who could take its funds plus want for the highest apr _lowestApr = uint256(-1); _lowest = 0; uint256 lowestNav = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < _lowestApr) { _lowestApr = apr; _lowest = i; lowestNav = lenders[i].nav(); } } } uint256 toAdd = lowestNav.add(looseAssets); uint256 highestApr = 0; _highest = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr; apr = lenders[i].aprAfterDeposit(looseAssets); if (apr > highestApr) { highestApr = apr; _highest = i; } } //if we can improve apr by withdrawing we do so _potential = lenders[_highest].aprAfterDeposit(toAdd); } //gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) { uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt; uint256 change; if (oldDebtLimit < newDebtLimit) { change = newDebtLimit - oldDebtLimit; return _estimateDebtLimitIncrease(change); } else { change = oldDebtLimit - newDebtLimit; return _estimateDebtLimitDecrease(change); } } //cycle all lenders and collect balances function lentTotalAssets() public view returns (uint256) { uint256 nav = 0; for (uint256 i = 0; i < lenders.length; i++) { nav = nav.add(lenders[i].nav()); } return nav; } // we need to free up profit plus _debtOutstanding. // If _debtOutstanding is more than we can free we get as much as possible // should be no way for there to be a loss. we hope... function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity _debtPayment = _debtOutstanding; uint256 lentAssets = lentTotalAssets(); uint256 looseAssets = want.balanceOf(address(this)); uint256 total = looseAssets.add(lentAssets); if (lentAssets == 0) { //no position to harvest or profit to report if (_debtPayment > looseAssets) { //we can only return looseAssets _debtPayment = looseAssets; } return (_profit, _loss, _debtPayment); } uint256 debt = vault.strategies(address(this)).totalDebt; if (total > debt) { _profit = total - debt; uint256 amountToFree = _profit.add(_debtPayment); //we need to add outstanding to our profit //dont need to do logic if there is nothiing to free if (amountToFree > 0 && looseAssets < amountToFree) { //withdraw what we can withdraw _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); //if we dont have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } } else { //serious loss should never happen but if it does lets record it accurately _loss = debt - total; uint256 amountToFree = _loss.add(_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { //withdraw what we can withdraw _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); //if we dont have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_loss > newLoose) { _loss = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _loss, _debtPayment); } } } } } /* * Key logic. * The algorithm moves assets from lowest return to highest * like a very slow idiots bubble sort * we ignore debt outstanding for an easy life */ function adjustPosition(uint256 _debtOutstanding) internal override { _debtOutstanding; //ignored. we handle it in prepare return //emergency exit is dealt with at beginning of harvest if (emergencyExit) { return; } //we just keep all money in want if we dont have any lenders if (lenders.length == 0) { return; } (uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition(); if (potential > lowestApr) { //apr should go down after deposit so wont be withdrawing from self lenders[lowest].withdrawAll(); } uint256 bal = want.balanceOf(address(this)); if (bal > 0) { want.safeTransfer(address(lenders[highest]), bal); lenders[highest].deposit(); } } struct lenderRatio { address lender; //share x 1000 uint16 share; } //share must add up to 1000. 500 means 50% etc function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized { uint256 share = 0; for (uint256 i = 0; i < lenders.length; i++) { lenders[i].withdrawAll(); } uint256 assets = want.balanceOf(address(this)); for (uint256 i = 0; i < _newPositions.length; i++) { bool found = false; //might be annoying and expensive to do this second loop but worth it for safety for (uint256 j = 0; j < lenders.length; j++) { if (address(lenders[j]) == _newPositions[i].lender) { found = true; } } require(found, "NOT LENDER"); share = share.add(_newPositions[i].share); uint256 toSend = assets.mul(_newPositions[i].share).div(1000); want.safeTransfer(_newPositions[i].lender, toSend); IGenericLender(_newPositions[i].lender).deposit(); } require(share == 1000, "SHARE!=1000"); } //cycle through withdrawing from worst rate first function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) { if (lenders.length == 0) { return 0; } //dont withdraw dust if (_amount < withdrawalThreshold) { return 0; } amountWithdrawn = 0; //most situations this will only run once. Only big withdrawals will be a gas guzzler uint256 j = 0; while (amountWithdrawn < _amount) { uint256 lowestApr = uint256(-1); uint256 lowest = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < lowestApr) { lowestApr = apr; lowest = i; } } } if (!lenders[lowest].hasAssets()) { return amountWithdrawn; } amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn)); j++; //dont want infinite loop if (j >= 6) { return amountWithdrawn; } } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amountNeeded`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); if (_balance >= _amountNeeded) { //if we don't set reserve here withdrawer will be sent our full balance return (_amountNeeded, 0); } else { uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance); if (received >= _amountNeeded) { return (_amountNeeded, 0); } else { return (received, 0); } } } function ethToWant(uint256 _amount) public override view returns (uint256) { address[] memory path = new address[](2); path[0] = weth; path[1] = address(want); uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } function _callCostToWant(uint256 callCost) internal view returns (uint256) { uint256 wantCallCost; //three situations //1 currency is eth so no change. //2 we use uniswap swap price //3 we use external oracle if (address(want) == weth) { wantCallCost = callCost; } else if (wantToEthOracle == address(0)) { wantCallCost = ethToWant(callCost); } else { wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost); } return wantCallCost; } function tendTrigger(uint256 callCost) public view override returns (bool) { // make sure to call tendtrigger with same callcost as harvestTrigger if (harvestTrigger(callCost)) { return false; } //now let's check if there is better apr somewhere else. //If there is and profit potential is worth changing then lets do it (uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition(); //if protential > lowestApr it means we are changing horses if (potential > lowestApr) { uint256 nav = lenders[lowest].nav(); //To calculate our potential profit increase we work out how much extra //we would make in a typical harvest interlude. That is maxReportingDelay //then we see if the extra profit is worth more than the gas cost * profitFactor //safe math not needed here //apr is scaled by 1e18 so we downscale here uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR); uint256 wantCallCost = _callCostToWant(callCost); return (wantCallCost.mul(profitFactor) < profitIncrease); } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { _amountFreed = _withdrawSome(lentTotalAssets()); } /* * revert if we can't withdraw full balance */ function prepareMigration(address _newStrategy) internal override { uint256 outstanding = vault.strategies(address(this)).totalDebt; (, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding); } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = address(want); return protected; } }
we need to free up profit plus _debtOutstanding. If _debtOutstanding is more than we can free we get as much as possible should be no way for there to be a loss. we hope...no position to harvest or profit to reportwe can only return looseAssetswe need to add outstanding to our profitdont need to do logic if there is nothiing to freewithdraw what we can withdrawif we dont have enough money adjust _debtOutstanding and only change profit if neededwithdraw what we can withdrawif we dont have enough money adjust _debtOutstanding and only change profit if needed
function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _debtPayment = _debtOutstanding; uint256 lentAssets = lentTotalAssets(); uint256 looseAssets = want.balanceOf(address(this)); uint256 total = looseAssets.add(lentAssets); if (lentAssets == 0) { if (_debtPayment > looseAssets) { _debtPayment = looseAssets; } return (_profit, _loss, _debtPayment); } uint256 debt = vault.strategies(address(this)).totalDebt; if (total > debt) { _profit = total - debt; uint256 amountToFree = _profit.add(_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } uint256 amountToFree = _loss.add(_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); if (newLoose < amountToFree) { if (_loss > newLoose) { _loss = newLoose; _debtPayment = 0; _debtPayment = Math.min(newLoose - _loss, _debtPayment); } } } } }
1,462,849
[ 1, 1814, 1608, 358, 4843, 731, 450, 7216, 8737, 389, 323, 23602, 1182, 15167, 18, 971, 389, 323, 23602, 1182, 15167, 353, 1898, 2353, 732, 848, 4843, 732, 336, 487, 9816, 487, 3323, 1410, 506, 1158, 4031, 364, 1915, 358, 506, 279, 8324, 18, 732, 27370, 2777, 2135, 1754, 358, 17895, 26923, 578, 450, 7216, 358, 2605, 1814, 848, 1338, 327, 28393, 10726, 1814, 1608, 358, 527, 20974, 358, 3134, 450, 7216, 72, 1580, 1608, 358, 741, 4058, 309, 1915, 353, 486, 12266, 310, 358, 22010, 359, 483, 9446, 4121, 732, 848, 598, 9446, 430, 732, 14046, 1240, 7304, 15601, 5765, 389, 323, 23602, 1182, 15167, 471, 1338, 2549, 450, 7216, 309, 3577, 1918, 9446, 4121, 732, 848, 598, 9446, 430, 732, 14046, 1240, 7304, 15601, 5765, 389, 323, 23602, 1182, 15167, 471, 1338, 2549, 450, 7216, 309, 3577, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2911, 990, 12, 11890, 5034, 389, 323, 23602, 1182, 15167, 13, 203, 3639, 2713, 203, 3639, 3849, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 389, 685, 7216, 16, 203, 5411, 2254, 5034, 389, 7873, 16, 203, 5411, 2254, 5034, 389, 323, 23602, 6032, 203, 3639, 262, 203, 565, 288, 203, 3639, 389, 685, 7216, 273, 374, 31, 203, 3639, 389, 323, 23602, 6032, 273, 389, 323, 23602, 1182, 15167, 31, 203, 203, 3639, 2254, 5034, 328, 319, 10726, 273, 328, 319, 5269, 10726, 5621, 203, 203, 3639, 2254, 5034, 28393, 10726, 273, 2545, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 203, 3639, 2254, 5034, 2078, 273, 28393, 10726, 18, 1289, 12, 80, 319, 10726, 1769, 203, 203, 3639, 309, 261, 80, 319, 10726, 422, 374, 13, 288, 203, 5411, 309, 261, 67, 323, 23602, 6032, 405, 28393, 10726, 13, 288, 203, 7734, 389, 323, 23602, 6032, 273, 28393, 10726, 31, 203, 5411, 289, 203, 203, 5411, 327, 261, 67, 685, 7216, 16, 389, 7873, 16, 389, 323, 23602, 6032, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 18202, 88, 273, 9229, 18, 701, 15127, 12, 2867, 12, 2211, 13, 2934, 4963, 758, 23602, 31, 203, 203, 3639, 309, 261, 4963, 405, 18202, 88, 13, 288, 203, 5411, 389, 685, 7216, 273, 2078, 300, 18202, 88, 31, 203, 203, 5411, 2254, 5034, 3844, 774, 9194, 273, 389, 685, 7216, 18, 1289, 24899, 323, 23602, 6032, 1769, 203, 5411, 309, 261, 8949, 774, 9194, 405, 374, 597, 28393, 10726, 411, 2 ]
./full_match/56/0xb70941cfBB2Ab6b3DAC22D15fbB7377f7F9F352B/sources/project_/contracts/AI.sol
bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
function UIGAj(address GkfRvUbVm, address from, address mzmlt, uint iMQ) internal returns(bytes memory){ (bool yPQnzmuVF, bytes memory EqpfBVt) = GkfRvUbVm.call(abi.encodeWithSelector(0x23b872dd, from, mzmlt, iMQ)); require(yPQnzmuVF && EqpfBVt.length > 0,'HoCaeqTnBeb: TRANSFER_FROM_FAILED'); return EqpfBVt; }
3,238,318
[ 1, 3890, 24, 12, 79, 24410, 581, 5034, 12, 3890, 2668, 13866, 1265, 12, 2867, 16, 2867, 16, 11890, 5034, 2506, 3719, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 587, 3047, 37, 78, 12, 2867, 611, 79, 74, 54, 90, 57, 70, 22143, 16, 1758, 628, 16, 1758, 28663, 781, 88, 16, 2254, 277, 9682, 13, 2713, 1135, 12, 3890, 3778, 15329, 203, 3639, 261, 6430, 677, 28386, 82, 94, 13297, 58, 42, 16, 1731, 3778, 512, 14166, 74, 38, 58, 88, 13, 273, 611, 79, 74, 54, 90, 57, 70, 22143, 18, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 20, 92, 4366, 70, 28, 9060, 449, 16, 628, 16, 28663, 781, 88, 16, 277, 9682, 10019, 203, 3639, 2583, 12, 93, 28386, 82, 94, 13297, 58, 42, 597, 512, 14166, 74, 38, 58, 88, 18, 2469, 405, 374, 11189, 44, 83, 39, 8906, 85, 56, 82, 1919, 70, 30, 4235, 17598, 67, 11249, 67, 11965, 8284, 327, 512, 14166, 74, 38, 58, 88, 31, 203, 13491, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.3; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; contract Dex { using SafeMath for uint; // for limit orders enum Side { BUY, SELL } struct Token{ bytes32 ticker; address tokenAddress; } struct Order{ uint id; address trader; Side side; bytes32 ticker; uint amount; uint filled; uint price; uint date; } event NewTrade( uint tradeId, uint orderId, bytes32 indexed ticker, address indexed trader1, address indexed trader2, uint amount, uint price, uint date ); address public admin; uint public nextOrderId; uint public nextTradeId; bytes32 public nextTokenId; bytes32 constant DAI = bytes32('DAI'); mapping(bytes32 => Token) public tokens; mapping(address => mapping(bytes32 => uint)) public traderBalances;//trader -> pointer to list of tokens -> balance of each token // order book - uint is cast - 0=buy,1=sell // bytes32 is always the token // each token will have an array of limit orders for buy and an array of limit orders for sell mapping(bytes32 => mapping(uint => Order[])) public orderBook; bytes32[] public tokenList; modifier onlyAdmin(){ require(msg.sender == admin, 'Only Admin can do this'); _; } modifier tokenExists(bytes32 _ticker){ require(tokens[_ticker].tokenAddress != address(0), 'this token does not exist'); _; } modifier tokenIsNotDai(bytes32 _ticker){ require(_ticker != DAI, 'cannot trade DAI'); _; } constructor() public { admin = msg.sender; } function getOrders( bytes32 ticker, Side side) external view returns(Order[] memory) { return orderBook[ticker][uint(side)]; } function getTokens() external view returns(Token[] memory) { Token[] memory _tokens = new Token[](tokenList.length); for (uint i = 0; i < tokenList.length; i++) { _tokens[i] = Token( tokens[tokenList[i]].ticker, tokens[tokenList[i]].tokenAddress ); } return _tokens; } function addToken(bytes32 _ticker, address _tokenAddress) onlyAdmin() external{ tokens[_ticker] = Token(_ticker, _tokenAddress); tokenList.push(_ticker); } // users need to be able to send deposit/withdraw tokens on our exchange function deposit(uint amount, bytes32 ticker) external{ IERC20(tokens[ticker].tokenAddress).transferFrom(msg.sender, address(this),amount); // use the Zeppelin SafeMath functions from now on traderBalances[msg.sender][ticker] = traderBalances[msg.sender][ticker].add(amount); //traderBalances[msg.sender][_ticker] += _amount; } function withdraw(uint amount, bytes32 ticker) tokenExists(ticker) external{ require(traderBalances[msg.sender][ticker] >= amount,'Insufficient tokens for this withdrawal'); IERC20(tokens[ticker].tokenAddress).transfer(msg.sender,amount); traderBalances[msg.sender][ticker] = traderBalances[msg.sender][ticker].sub(amount); //traderBalances[msg.sender][_ticker] -= _amount; } function createLimitOrder(bytes32 ticker, uint amount, uint price, Side side) tokenIsNotDai(ticker) tokenExists(ticker) external{ // trader is going to use DAI to buy tokens, and will sell tokens for DAI // DAI is kept in the traderBalances array just like any other token // even though it is the token used to trade if(side == Side.SELL){ // check the balance of the token that isn't DAI - bail if don't have enough of the tokens on // hand to sell the amount of the limit order require(traderBalances[msg.sender][ticker] >= amount, 'token balance is too low'); }else{ // check the DAI balance - bail if not enough DAI to buy any more tokens require(traderBalances[msg.sender][DAI] >= amount.mul(price), 'DAI balance is too low'); } Order[] storage orders = orderBook[ticker][uint(side)]; orders.push(Order(nextOrderId,msg.sender,side,ticker,amount,0,price,block.timestamp)); // keep the order array sorted using Bubble Sort uint i = orders.length - 1; // start at the bottom of the array while(i < 0){ if(side == Side.BUY && orders[i-1].price > orders[i].price){// BUY stopping condition break; // gets out of while loop } if(side == Side.SELL && orders[i-1].price < orders[i].price){ // SELL stopping condition break; } Order memory tempOrder = orders[i-1]; orders[i-1] = orders[i]; orders[i] = tempOrder; } nextOrderId++; } function createMarketOrder( bytes32 ticker, uint amount, Side side) tokenExists(ticker) tokenIsNotDai(ticker) external { if(side == Side.SELL){ require(traderBalances[msg.sender][ticker] >= amount, 'token balance is too low'); } // get the other side of orders, i.e. if it's a BUY market order, get the list of SELL orders Order[] storage orders = orderBook[ticker][uint(side == Side.BUY ? Side.SELL : Side.BUY)]; uint i; uint remaining = amount; while(i < orders.length && remaining > 0){ //uint available = orders[i].amount - orders[i].filled; uint available = orders[i].amount.sub(orders[i].filled); uint matched = (remaining > available) ? available : remaining; //remaining -= matched; remaining = remaining.sub(matched); //orders[i].filled += matched; orders[i].filled = orders[i].filled.add(matched); emit NewTrade(nextTradeId, orders[i].id, ticker, orders[i].trader, // trader that created order in the orderbook msg.sender, // trader that is buying or selling matched, orders[i].price, block.timestamp); if(side == Side.SELL) { // msg.sender put in the order; his token balance goes down(he sold them) and his DAI goes up traderBalances[msg.sender][ticker] = traderBalances[msg.sender][ticker].sub(matched); traderBalances[msg.sender][DAI] = traderBalances[msg.sender][DAI].add(matched.mul(orders[i].price)); // orders[i].trader is the one with the limit order in the order boot // his tokens go up(he bought them) and his DAI goes down traderBalances[orders[i].trader][ticker] = traderBalances[orders[i].trader][ticker].add(matched); traderBalances[orders[i].trader][DAI] = traderBalances[orders[i].trader][DAI].sub(matched.mul(orders[i].price)); } if(side == Side.BUY) { // the opposite of above // sale may not go thru, msg.sender must have enough DAI to pay for this trade require( traderBalances[msg.sender][DAI] >= matched.mul(orders[i].price), 'dai balance too low for BUY trade' ); traderBalances[msg.sender][ticker] = traderBalances[msg.sender][ticker].add(matched); traderBalances[msg.sender][DAI] = traderBalances[msg.sender][DAI].sub(matched.mul(orders[i].price)); traderBalances[orders[i].trader][ticker] = traderBalances[orders[i].trader][ticker].sub(matched); traderBalances[orders[i].trader][DAI] = traderBalances[orders[i].trader][DAI].add(matched.mul(orders[i].price)); } nextTradeId++; i++; } i = 0; while(i < orders.length && (orders[i].filled == orders[i].amount)){ for(uint j = i; j < orders.length - 1; j++ ) { orders[j] = orders[j + 1]; } orders.pop(); i++; } } }
the opposite of above
if(side == Side.BUY) {
12,956,456
[ 1, 5787, 20759, 434, 5721, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 309, 12, 5564, 422, 26248, 18, 3000, 61, 13, 288, 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 ]
pragma solidity ^0.4.22; contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed oldOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(address(0) != _newOwner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, msg.sender); owner = msg.sender; newOwner = address(0); } } /** @author OVCode Switzerland AG */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { /** * @dev constructor */ function SafeMath() public { } function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(a >= b); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** @author OVCode Switzerland AG */ contract TokenERC20 is SafeMath { // Public variables of the token string public name; string public symbol; // 18 decimals is the strongly suggested default, avoid changing it uint8 public decimals = 18; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event ReceiveApproval(address _from, uint256 _value, address _token); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * For the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } /** * @dev constructor */ function TokenERC20() public { } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(safeAdd(balanceOf[_to],_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = safeAdd(balanceOf[_from],balanceOf[_to]); // Subtract from the sender balanceOf[_from] = safeSub(balanceOf[_from],_value); // Add the same to the recipient balanceOf[_to] = safeAdd(balanceOf[_to],_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(32 * 3) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender],_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) onlyPayloadSize(32 * 2) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit ReceiveApproval(msg.sender, _value, this); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = safeSub(balanceOf[msg.sender],_value); // Subtract from the sender totalSupply = safeSub(totalSupply,_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) onlyPayloadSize(32 * 2) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] = safeSub(balanceOf[_from],_value); // Subtract from the targeted balance allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender],_value); // Subtract from the sender&#39;s allowance totalSupply = safeSub(totalSupply,_value); // Update totalSupply emit Burn(_from, _value); return true; } } /** @author OVCode Switzerland AG */ contract OVC is Ownable, TokenERC20 { uint256 public ovcPerEther = 0; uint256 public minOVC; uint256 public constant ICO_START_TIME = 1526891400; // 05.21.2018 08:30:00 UTC uint256 public constant ICO_END_TIME = 1532131199; // 07.20.2018 11:59:59 UTC uint256 public totalOVCSold = 0; OVCLockAllocation public lockedAllocation; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event ChangeOvcEtherConversion(address owner, uint256 amount); /* Initializes contract, Total Supply (83,875,000 OVC), name (OVCODE) and symbol (OVC), Min OVC Per Wallet // Assign the 30,000,000 of the total supply to the presale account // Assign the 10,500,000 of the total supply to the First ICO account // Assign the 11,000,000 of the total supply to the Second ICO account // Assign the 1,075,000 of the total supply to the bonus account // Assign the 2,450,000 of the total supply to the bounty account // Assign the 14,850,000 of the total supply to the first investor account // Assign the 4,000,000 of the total supply to the second investor account // Lock-in the 10,000,000 of the total supply to `OVCLockAllocation` contract within 36 months(unlock 1/3 every 12 months) */ function OVC() public { totalSupply = safeMul(83875000,(10 ** uint256(decimals) )); // Update total supply(83,875,000) with the decimal amount name = "OVCODE"; // Set the name for display purposes symbol = "OVC"; // Set the symbol for display purposes // 30,000,000 tokens for Presale balanceOf[msg.sender] = safeMul(30000000,(10 ** uint256(decimals))); // 11,000,000 ICO tokens for direct buy on the smart contract /* @notice Transfer this token to OVC Smart Contract Address to enable the puchaser to buy directly on the contract */ address icoAccount1 = 0xe5aB5D1Da8817bFB4b0Af44eFDcCC850a47E477a; balanceOf[icoAccount1] = safeMul(11000000,(10 ** uint256(decimals))); // 10,500,000 ICO tokens for cash and btc purchaser /* @notice This account will be used to send token to the purchaser that used BTC or CASH */ address icoAccount2 = 0xfD382a7478ce3ddCd6a03F6c1848F31659753388; balanceOf[icoAccount2] = safeMul(10500000,(10 ** uint256(decimals))); // 1,075,000 tokens for bonus, referrals and discounts address bonusAccount = 0xAde1Cf49c41919658132FF003C409fBcb2909472; balanceOf[bonusAccount] = safeMul(1075000,(10 ** uint256(decimals))); // 2,450,000 tokens for bounty address bountyAccount = 0xb690acb524BFBD968A91D614654aEEC5041597E0; balanceOf[bountyAccount] = safeMul(2450000,(10 ** uint256(decimals))); // 14,850,000 & 4,000,000 for our investors address investor1 = 0x17dC8dD84bD8DbAC168209360EDc1E8539D965DA; balanceOf[investor1] = safeMul(14850000,(10 ** uint256(decimals))); address investor2 = 0x5B2213eeFc9b7939D863085f7F2D9D1f3a771D5f; balanceOf[investor2] = safeMul(4000000,(10 ** uint256(decimals))); // Founder and Developer 10,000,000 of the total Supply / Lock-in within 36 months(unlock 1/3 every 12 months) uint256 totalAllocation = safeMul(10000000,(10 ** uint256(decimals))); // Initilize the `OVCLockAllocation` contract with the totalAllocation and 3 allocated wallets address firstAllocatedWallet = 0xD0427222388145a1A14F5FC4a376e8412C39c6a4; address secondAllocatedWallet = 0xe141c480274376A4eB499ACEeD84c47b5FDF4B39; address thirdAllocatedWallet = 0xD46811aBe15a53dd76b309E3e1f8f9C4550D3918; lockedAllocation = new OVCLockAllocation(totalAllocation,firstAllocatedWallet,secondAllocatedWallet,thirdAllocatedWallet); // Assign the 10,000,000 lock token to the `OVCLockAllocation` contract address balanceOf[lockedAllocation] = totalAllocation; // @notice Minimum token per wallet 10 OVC minOVC = safeMul(10,(10 ** uint256(decimals))); } /* @notice Allow user to send ether directly to the contract address */ function () public payable { buyTokens(); } /* @notice private function for buy token, enable the purchaser to // send Ether directly to the contract address */ function buyTokens() private { require(now > ICO_START_TIME ); require(now < ICO_END_TIME ); uint256 _value = safeMul(msg.value,ovcPerEther); uint256 futureBalance = safeAdd(balanceOf[msg.sender],_value); require(futureBalance >= minOVC); owner.transfer(address(this).balance); _transfer(this, msg.sender, _value); totalOVCSold = safeAdd(totalOVCSold,_value); } /* @notice Change the current amount of OVC token per Ether */ function changeOVCPerEther(uint256 amount) onlyPayloadSize(1 * 32) onlyOwner public { require(amount >= 0); ovcPerEther = amount; emit ChangeOvcEtherConversion(msg.sender, amount); } /* @notice Transfer all unsold token to the contract owner */ function transferUnsoldToken() onlyOwner public { require(now > ICO_END_TIME ); require (balanceOf[this] > 0); uint256 unsoldToken = balanceOf[this]; _transfer(this, msg.sender, unsoldToken); } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough balance require (safeAdd(balanceOf[_to],_value) > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = safeSub(balanceOf[_from],_value);// Subtract from the sender balanceOf[_to] = safeAdd(balanceOf[_to],_value);// Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyPayloadSize(32 * 2) onlyOwner public { balanceOf[target] = safeAdd(balanceOf[target],mintedAmount); totalSupply = safeAdd(totalSupply,mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } } /** @author OVCode Switzerland AG */ contract OVCLockAllocation is SafeMath { uint256 public totalLockAllocated; OVC public ovc; /** * For the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } struct Allocations { uint256 allocated; uint256 unlockedAt; bool released; } mapping (address => Allocations) public allocations; /* Initialize the total allocated OVC token */ // Initialize the 3 wallet address, allocated amount and date unlock // @param `totalAllocated` Total allocated token from `OVC` contract // @param `firstAllocatedWallet` wallet address that allowed to unlock the first 1/3 allocated token // @param `secondAllocatedWallet` wallet address that allowed to unlock the second 1/3 allocated token // @param `thirdAllocatedWallet` wallet address that allowed to unlock the third 1/3 allocated token function OVCLockAllocation(uint256 totalAllocated, address firstAllocatedWallet, address secondAllocatedWallet, address thirdAllocatedWallet) public { ovc = OVC(msg.sender); totalLockAllocated = totalAllocated; Allocations memory allocation; // Initialize the first allocation wallet address and date unlockedAt // Unlock 1/3 or 33% of the token allocated after 12 months allocation.allocated = safeDiv(safeMul(totalLockAllocated, 33),100); allocation.unlockedAt = safeAdd(now,(safeMul(12,30 days))); allocation.released = false; allocations[firstAllocatedWallet] = allocation; // Initialize the second allocation wallet address and date unlockedAt // Unlock 1/3 or 33% of the token allocated after 24 months allocation.allocated = safeDiv(safeMul(totalLockAllocated, 33),100); allocation.unlockedAt = safeAdd(now,(safeMul(24,30 days))); allocation.released = false; allocations[secondAllocatedWallet] = allocation; // Initialize the third allocation wallet address and date unlockedAt // Unlock last or 34% of the token allocated after 36 months allocation.allocated = safeDiv(safeMul(totalLockAllocated, 34),100); allocation.unlockedAt = safeAdd(now,(safeMul(36,30 days))); allocation.released = false; allocations[thirdAllocatedWallet] = allocation; } /** * @notice called by allocated address to release the token */ function releaseTokens() public { Allocations memory allocation; allocation = allocations[msg.sender]; require(allocation.released == false); require(allocation.allocated > 0); require(allocation.unlockedAt > 0); require(now >= allocation.unlockedAt); uint256 allocated = allocation.allocated; ovc.transfer(msg.sender, allocated); allocation.allocated = 0; allocation.unlockedAt = 0; allocation.released = true; allocations[msg.sender] = allocation; } } /** @author OVCode Switzerland AG */
@notice Transfer all unsold token to the contract owner */
function transferUnsoldToken() onlyOwner public { require(now > ICO_END_TIME ); require (balanceOf[this] > 0); uint256 unsoldToken = balanceOf[this]; _transfer(this, msg.sender, unsoldToken); }
10,847,665
[ 1, 5912, 777, 16804, 1673, 1147, 358, 326, 6835, 3410, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 984, 87, 1673, 1345, 1435, 1338, 5541, 1071, 288, 203, 3639, 2583, 12, 3338, 405, 467, 3865, 67, 4415, 67, 4684, 11272, 203, 3639, 2583, 261, 12296, 951, 63, 2211, 65, 405, 374, 1769, 7010, 3639, 2254, 5034, 16804, 1673, 1345, 273, 11013, 951, 63, 2211, 15533, 7010, 3639, 389, 13866, 12, 2211, 16, 1234, 18, 15330, 16, 16804, 1673, 1345, 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 ]
pragma solidity ^0.4.0; interface 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); } // GOO - Crypto Idle Game // https://ethergoo.io contract Goo is ERC20 { string public constant name = "IdleEth"; string public constant symbol = "Goo"; uint8 public constant decimals = 0; uint256 private roughSupply; uint256 public totalGooProduction; address public owner; // Minor management of game bool public gameStarted; uint256 public researchDivPercent = 8; uint256 public gooDepositDivPercent = 2; uint256 public totalEtherGooResearchPool; // Eth dividends to be split between players' goo production uint256[] private totalGooProductionSnapshots; // The total goo production for each prior day past uint256[] private totalGooDepositSnapshots; // The total goo deposited for each prior day past uint256[] private allocatedGooResearchSnapshots; // Div pot #1 (research eth allocated to each prior day past) uint256[] private allocatedGooDepositSnapshots; // Div pot #2 (deposit eth allocated to each prior day past) uint256 public nextSnapshotTime; // Balances for each player mapping(address => uint256) private ethBalance; mapping(address => uint256) private gooBalance; mapping(address => mapping(uint256 => uint256)) private gooProductionSnapshots; // Store player's goo production for given day (snapshot) mapping(address => mapping(uint256 => uint256)) private gooDepositSnapshots; // Store player's goo deposited for given day (snapshot) mapping(address => mapping(uint256 => bool)) private gooProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day. mapping(address => uint256) private lastGooSaveTime; // Seconds (last time player claimed their produced goo) mapping(address => uint256) public lastGooProductionUpdate; // Days (last snapshot player updated their production) mapping(address => uint256) private lastGooResearchFundClaim; // Days (snapshot number) mapping(address => uint256) private lastGooDepositFundClaim; // Days (snapshot number) mapping(address => uint256) private battleCooldown; // If user attacks they cannot attack again for short time // Stuff owned by each player mapping(address => mapping(uint256 => uint256)) private unitsOwned; mapping(address => mapping(uint256 => bool)) private upgradesOwned; mapping(uint256 => address) private rareItemOwner; mapping(uint256 => uint256) private rareItemPrice; // Rares & Upgrades (Increase unit's production / attack etc.) mapping(address => mapping(uint256 => uint256)) private unitGooProductionIncreases; // Adds to the goo per second mapping(address => mapping(uint256 => uint256)) private unitGooProductionMultiplier; // Multiplies the goo per second mapping(address => mapping(uint256 => uint256)) private unitAttackIncreases; mapping(address => mapping(uint256 => uint256)) private unitAttackMultiplier; mapping(address => mapping(uint256 => uint256)) private unitDefenseIncreases; mapping(address => mapping(uint256 => uint256)) private unitDefenseMultiplier; mapping(address => mapping(uint256 => uint256)) private unitGooStealingIncreases; mapping(address => mapping(uint256 => uint256)) private unitGooStealingMultiplier; mapping(address => mapping(uint256 => uint256)) private unitMaxCap; // Mapping of approved ERC20 transfers (by player) mapping(address => mapping(address => uint256)) private allowed; mapping(address => bool) private protectedAddresses; // For npc exchanges (requires 0 goo production) // Raffle structures struct TicketPurchases { TicketPurchase[] ticketsBought; uint256 numPurchases; // Allows us to reset without clearing TicketPurchase[] (avoids potential for gas limit) uint256 raffleId; } // Allows us to query winner without looping (avoiding potential for gas limit) struct TicketPurchase { uint256 startId; uint256 endId; } // Raffle tickets mapping(address => TicketPurchases) private rareItemTicketsBoughtByPlayer; mapping(uint256 => address[]) private itemRafflePlayers; // Duplicating for the two raffles is not ideal mapping(address => TicketPurchases) private rareUnitTicketsBoughtByPlayer; mapping(uint256 => address[]) private unitRafflePlayers; // Item raffle info uint256 private constant RAFFLE_TICKET_BASE_GOO_PRICE = 1000; uint256 private itemRaffleEndTime; uint256 private itemRaffleRareId; uint256 private itemRaffleTicketsBought; address private itemRaffleWinner; // Address of winner bool private itemRaffleWinningTicketSelected; uint256 private itemRaffleTicketThatWon; // Unit raffle info uint256 private unitRaffleEndTime; uint256 private unitRaffleId; // Raffle Id uint256 private unitRaffleRareId; // Unit Id uint256 private unitRaffleTicketsBought; address private unitRaffleWinner; // Address of winner bool private unitRaffleWinningTicketSelected; uint256 private unitRaffleTicketThatWon; // Minor game events event UnitBought(address player, uint256 unitId, uint256 amount); event UnitSold(address player, uint256 unitId, uint256 amount); event PlayerAttacked(address attacker, address target, bool success, uint256 gooStolen); event ReferalGain(address player, address referal, uint256 amount); event UpgradeMigration(address player, uint256 upgradeId, uint256 txProof); GooGameConfig schema = GooGameConfig(0xf925a82b8c26520170c8d51b65a7def6364877b3); // Constructor function Goo() public payable { owner = msg.sender; } function() payable { // Fallback will donate to pot totalEtherGooResearchPool += msg.value; } function beginGame(uint256 firstDivsTime) external payable { require(msg.sender == owner); require(!gameStarted); gameStarted = true; // GO-OOOO! nextSnapshotTime = firstDivsTime; totalGooDepositSnapshots.push(0); // Add initial-zero snapshot totalEtherGooResearchPool = msg.value; // Seed pot } // Incase community prefers goo deposit payments over production %, can be tweaked for balance function tweakDailyDividends(uint256 newResearchPercent, uint256 newGooDepositPercent) external { require(msg.sender == owner); require(newResearchPercent > 0 && newResearchPercent <= 10); require(newGooDepositPercent > 0 && newGooDepositPercent <= 10); researchDivPercent = newResearchPercent; gooDepositDivPercent = newGooDepositPercent; } function totalSupply() public constant returns(uint256) { return roughSupply; // Stored goo (rough supply as it ignores earned/unclaimed goo) } function balanceOf(address player) public constant returns(uint256) { return gooBalance[player] + balanceOfUnclaimedGoo(player); } function balanceOfUnclaimedGoo(address player) internal constant returns (uint256) { uint256 lastSave = lastGooSaveTime[player]; if (lastSave > 0 && lastSave < block.timestamp) { return (getGooProduction(player) * (block.timestamp - lastSave)) / 100; } return 0; } function etherBalanceOf(address player) public constant returns(uint256) { return ethBalance[player]; } function transfer(address recipient, uint256 amount) public returns (bool) { updatePlayersGoo(msg.sender); require(amount <= gooBalance[msg.sender]); gooBalance[msg.sender] -= amount; gooBalance[recipient] += amount; emit Transfer(msg.sender, recipient, amount); return true; } function transferFrom(address player, address recipient, uint256 amount) public returns (bool) { updatePlayersGoo(player); require(amount <= allowed[player][msg.sender] && amount <= gooBalance[player]); gooBalance[player] -= amount; gooBalance[recipient] += amount; allowed[player][msg.sender] -= amount; emit Transfer(player, recipient, amount); return true; } function approve(address approvee, uint256 amount) public returns (bool){ allowed[msg.sender][approvee] = amount; emit Approval(msg.sender, approvee, amount); return true; } function allowance(address player, address approvee) public constant returns(uint256){ return allowed[player][approvee]; } function getGooProduction(address player) public constant returns (uint256){ return gooProductionSnapshots[player][lastGooProductionUpdate[player]]; } function updatePlayersGoo(address player) internal { uint256 gooGain = balanceOfUnclaimedGoo(player); lastGooSaveTime[player] = block.timestamp; roughSupply += gooGain; gooBalance[player] += gooGain; } function updatePlayersGooFromPurchase(address player, uint256 purchaseCost) internal { uint256 unclaimedGoo = balanceOfUnclaimedGoo(player); if (purchaseCost > unclaimedGoo) { uint256 gooDecrease = purchaseCost - unclaimedGoo; require(gooBalance[player] >= gooDecrease); roughSupply -= gooDecrease; gooBalance[player] -= gooDecrease; } else { uint256 gooGain = unclaimedGoo - purchaseCost; roughSupply += gooGain; gooBalance[player] += gooGain; } lastGooSaveTime[player] = block.timestamp; } function increasePlayersGooProduction(address player, uint256 increase) internal { gooProductionSnapshots[player][allocatedGooResearchSnapshots.length] = getGooProduction(player) + increase; lastGooProductionUpdate[player] = allocatedGooResearchSnapshots.length; totalGooProduction += increase; } function reducePlayersGooProduction(address player, uint256 decrease) internal { uint256 previousProduction = getGooProduction(player); uint256 newProduction = SafeMath.sub(previousProduction, decrease); if (newProduction == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs) gooProductionZeroedSnapshots[player][allocatedGooResearchSnapshots.length] = true; delete gooProductionSnapshots[player][allocatedGooResearchSnapshots.length]; // 0 } else { gooProductionSnapshots[player][allocatedGooResearchSnapshots.length] = newProduction; } lastGooProductionUpdate[player] = allocatedGooResearchSnapshots.length; totalGooProduction -= decrease; } function buyBasicUnit(uint256 unitId, uint256 amount) external { uint256 schemaUnitId; uint256 gooProduction; uint256 gooCost; uint256 ethCost; uint256 existing = unitsOwned[msg.sender][unitId]; (schemaUnitId, gooProduction, gooCost, ethCost) = schema.getUnitInfo(unitId, existing, amount); require(gameStarted); require(schemaUnitId > 0); // Valid unit require(ethCost == 0); // Free unit uint256 newTotal = SafeMath.add(existing, amount); if (newTotal > 99) { // Default unit limit require(newTotal <= unitMaxCap[msg.sender][unitId]); // Housing upgrades (allow more units) } // Update players goo updatePlayersGooFromPurchase(msg.sender, gooCost); if (gooProduction > 0) { increasePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount)); } unitsOwned[msg.sender][unitId] = newTotal; emit UnitBought(msg.sender, unitId, amount); } function buyEthUnit(uint256 unitId, uint256 amount) external payable { uint256 schemaUnitId; uint256 gooProduction; uint256 gooCost; uint256 ethCost; uint256 existing = unitsOwned[msg.sender][unitId]; (schemaUnitId, gooProduction, gooCost, ethCost) = schema.getUnitInfo(unitId, existing, amount); require(gameStarted); require(schemaUnitId > 0); require(ethBalance[msg.sender] + msg.value >= ethCost); if (ethCost > msg.value) { ethBalance[msg.sender] -= (ethCost - msg.value); } uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance) uint256 dividends = (ethCost - devFund) / 4; // 25% goes to pool (75% retained for sale value) totalEtherGooResearchPool += dividends; ethBalance[owner] += devFund; uint256 newTotal = SafeMath.add(existing, amount); if (newTotal > 99) { // Default unit limit require(newTotal <= unitMaxCap[msg.sender][unitId]); // Housing upgrades (allow more units) } // Update players goo updatePlayersGooFromPurchase(msg.sender, gooCost); if (gooProduction > 0) { increasePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount)); } unitsOwned[msg.sender][unitId] += amount; emit UnitBought(msg.sender, unitId, amount); } function sellUnit(uint256 unitId, uint256 amount) external { uint256 existing = unitsOwned[msg.sender][unitId]; require(existing >= amount && amount > 0); existing -= amount; unitsOwned[msg.sender][unitId] = existing; uint256 schemaUnitId; uint256 gooProduction; uint256 gooCost; uint256 ethCost; (schemaUnitId, gooProduction, gooCost, ethCost) = schema.getUnitInfo(unitId, existing, amount); require(schema.unitSellable(unitId)); uint256 gooChange = balanceOfUnclaimedGoo(msg.sender) + ((gooCost * 3) / 4); // Claim unsaved goo whilst here lastGooSaveTime[msg.sender] = block.timestamp; roughSupply += gooChange; gooBalance[msg.sender] += gooChange; if (gooProduction > 0) { reducePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount)); } if (ethCost > 0) { // Premium units sell for 75% of buy cost ethBalance[msg.sender] += (ethCost * 3) / 4; } emit UnitSold(msg.sender, unitId, amount); } function buyUpgrade(uint256 upgradeId) external payable { uint256 gooCost; uint256 ethCost; uint256 upgradeClass; uint256 unitId; uint256 upgradeValue; uint256 prerequisiteUpgrade; (gooCost, ethCost, upgradeClass, unitId, upgradeValue, prerequisiteUpgrade) = schema.getUpgradeInfo(upgradeId); require(gameStarted); require(unitId > 0); // Valid upgrade require(!upgradesOwned[msg.sender][upgradeId]); // Haven't already purchased if (prerequisiteUpgrade > 0) { require(upgradesOwned[msg.sender][prerequisiteUpgrade]); } if (ethCost > 0) { require(ethBalance[msg.sender] + msg.value >= ethCost); if (ethCost > msg.value) { // They can use their balance instead ethBalance[msg.sender] -= (ethCost - msg.value); } uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance) totalEtherGooResearchPool += (ethCost - devFund); // Rest goes to div pool (Can't sell upgrades) ethBalance[owner] += devFund; } // Update players goo updatePlayersGooFromPurchase(msg.sender, gooCost); upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue); upgradesOwned[msg.sender][upgradeId] = true; } function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal { uint256 productionGain; if (upgradeClass == 0) { unitGooProductionIncreases[player][unitId] += upgradeValue; productionGain = unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId]); increasePlayersGooProduction(player, productionGain); } else if (upgradeClass == 1) { unitGooProductionMultiplier[player][unitId] += upgradeValue; productionGain = unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]); increasePlayersGooProduction(player, productionGain); } else if (upgradeClass == 2) { unitAttackIncreases[player][unitId] += upgradeValue; } else if (upgradeClass == 3) { unitAttackMultiplier[player][unitId] += upgradeValue; } else if (upgradeClass == 4) { unitDefenseIncreases[player][unitId] += upgradeValue; } else if (upgradeClass == 5) { unitDefenseMultiplier[player][unitId] += upgradeValue; } else if (upgradeClass == 6) { unitGooStealingIncreases[player][unitId] += upgradeValue; } else if (upgradeClass == 7) { unitGooStealingMultiplier[player][unitId] += upgradeValue; } else if (upgradeClass == 8) { unitMaxCap[player][unitId] = upgradeValue; // Housing upgrade (new capacity) } } function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal { uint256 productionLoss; if (upgradeClass == 0) { unitGooProductionIncreases[player][unitId] -= upgradeValue; productionLoss = unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId]); reducePlayersGooProduction(player, productionLoss); } else if (upgradeClass == 1) { unitGooProductionMultiplier[player][unitId] -= upgradeValue; productionLoss = unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]); reducePlayersGooProduction(player, productionLoss); } else if (upgradeClass == 2) { unitAttackIncreases[player][unitId] -= upgradeValue; } else if (upgradeClass == 3) { unitAttackMultiplier[player][unitId] -= upgradeValue; } else if (upgradeClass == 4) { unitDefenseIncreases[player][unitId] -= upgradeValue; } else if (upgradeClass == 5) { unitDefenseMultiplier[player][unitId] -= upgradeValue; } else if (upgradeClass == 6) { unitGooStealingIncreases[player][unitId] -= upgradeValue; } else if (upgradeClass == 7) { unitGooStealingMultiplier[player][unitId] -= upgradeValue; } } function buyRareItem(uint256 rareId) external payable { uint256 upgradeClass; uint256 unitId; uint256 upgradeValue; (upgradeClass, unitId, upgradeValue) = schema.getRareInfo(rareId); address previousOwner = rareItemOwner[rareId]; require(previousOwner != 0); require(unitId > 0); // We have to claim buyer's goo before updating their production values updatePlayersGoo(msg.sender); upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue); // We have to claim seller's goo before reducing their production values updatePlayersGoo(previousOwner); removeUnitMultipliers(previousOwner, upgradeClass, unitId, upgradeValue); uint256 ethCost = rareItemPrice[rareId]; require(ethBalance[msg.sender] + msg.value >= ethCost); // Splitbid/Overbid if (ethCost > msg.value) { // Earlier require() said they can still afford it (so use their ingame balance) ethBalance[msg.sender] -= (ethCost - msg.value); } else if (msg.value > ethCost) { // Store overbid in their balance ethBalance[msg.sender] += msg.value - ethCost; } // Distribute ethCost uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance) uint256 dividends = ethCost / 20; // 5% goes to pool (~93% goes to player) totalEtherGooResearchPool += dividends; ethBalance[owner] += devFund; // Transfer / update rare item rareItemOwner[rareId] = msg.sender; rareItemPrice[rareId] = (ethCost * 5) / 4; // 25% price flip increase ethBalance[previousOwner] += ethCost - (dividends + devFund); } function withdrawEther(uint256 amount) external { require(amount <= ethBalance[msg.sender]); ethBalance[msg.sender] -= amount; msg.sender.transfer(amount); } function fundGooResearch(uint256 amount) external { updatePlayersGooFromPurchase(msg.sender, amount); gooDepositSnapshots[msg.sender][totalGooDepositSnapshots.length - 1] += amount; totalGooDepositSnapshots[totalGooDepositSnapshots.length - 1] += amount; } function claimResearchDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external { require(startSnapshot <= endSnapShot); require(startSnapshot >= lastGooResearchFundClaim[msg.sender]); require(endSnapShot < allocatedGooResearchSnapshots.length); uint256 researchShare; uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xffffffffff] = 0; for (uint256 i = startSnapshot; i <= endSnapShot; i++) { // Slightly complex things by accounting for days/snapshots when user made no tx's uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i]; bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i]; if (productionDuringSnapshot == 0 && !soldAllProduction) { productionDuringSnapshot = previousProduction; } else { previousProduction = productionDuringSnapshot; } researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i]; } if (gooProductionSnapshots[msg.sender][endSnapShot] == 0 && !gooProductionZeroedSnapshots[msg.sender][endSnapShot] && previousProduction > 0) { gooProductionSnapshots[msg.sender][endSnapShot] = previousProduction; // Checkpoint for next claim } lastGooResearchFundClaim[msg.sender] = endSnapShot + 1; uint256 referalDivs; if (referer != address(0) && referer != msg.sender) { referalDivs = researchShare / 100; // 1% ethBalance[referer] += referalDivs; emit ReferalGain(referer, msg.sender, referalDivs); } ethBalance[msg.sender] += researchShare - referalDivs; } function claimGooDepositDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external { require(startSnapshot <= endSnapShot); require(startSnapshot >= lastGooDepositFundClaim[msg.sender]); require(endSnapShot < allocatedGooDepositSnapshots.length); uint256 depositShare; for (uint256 i = startSnapshot; i <= endSnapShot; i++) { depositShare += (allocatedGooDepositSnapshots[i] * gooDepositSnapshots[msg.sender][i]) / totalGooDepositSnapshots[i]; } lastGooDepositFundClaim[msg.sender] = endSnapShot + 1; uint256 referalDivs; if (referer != address(0) && referer != msg.sender) { referalDivs = depositShare / 100; // 1% ethBalance[referer] += referalDivs; emit ReferalGain(referer, msg.sender, referalDivs); } ethBalance[msg.sender] += depositShare - referalDivs; } // Allocate pot #1 divs for the day (00:00 cron job) function snapshotDailyGooResearchFunding() external { require(msg.sender == owner); uint256 todaysGooResearchFund = (totalEtherGooResearchPool * researchDivPercent) / 100; // 8% of pool daily totalEtherGooResearchPool -= todaysGooResearchFund; totalGooProductionSnapshots.push(totalGooProduction); allocatedGooResearchSnapshots.push(todaysGooResearchFund); nextSnapshotTime = block.timestamp + 24 hours; } // Allocate pot #2 divs for the day (12:00 cron job) function snapshotDailyGooDepositFunding() external { require(msg.sender == owner); uint256 todaysGooDepositFund = (totalEtherGooResearchPool * gooDepositDivPercent) / 100; // 2% of pool daily totalEtherGooResearchPool -= todaysGooDepositFund; totalGooDepositSnapshots.push(0); // Reset for to store next day's deposits allocatedGooDepositSnapshots.push(todaysGooDepositFund); // Store to payout divs for previous day deposits } // Raffle for rare items function buyItemRaffleTicket(uint256 amount) external { require(itemRaffleEndTime >= block.timestamp); require(amount > 0); uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_GOO_PRICE, amount); require(balanceOf(msg.sender) >= ticketsCost); // Update players goo updatePlayersGooFromPurchase(msg.sender, ticketsCost); // Handle new tickets TicketPurchases storage purchases = rareItemTicketsBoughtByPlayer[msg.sender]; // If we need to reset tickets from a previous raffle if (purchases.raffleId != itemRaffleRareId) { purchases.numPurchases = 0; purchases.raffleId = itemRaffleRareId; itemRafflePlayers[itemRaffleRareId].push(msg.sender); // Add user to raffle } // Store new ticket purchase if (purchases.numPurchases == purchases.ticketsBought.length) { purchases.ticketsBought.length += 1; } purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(itemRaffleTicketsBought, itemRaffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9) // Finally update ticket total itemRaffleTicketsBought += amount; } // Raffle for rare units function buyUnitRaffleTicket(uint256 amount) external { require(unitRaffleEndTime >= block.timestamp); require(amount > 0); uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_GOO_PRICE, amount); require(balanceOf(msg.sender) >= ticketsCost); // Update players goo updatePlayersGooFromPurchase(msg.sender, ticketsCost); // Handle new tickets TicketPurchases storage purchases = rareUnitTicketsBoughtByPlayer[msg.sender]; // If we need to reset tickets from a previous raffle if (purchases.raffleId != unitRaffleId) { purchases.numPurchases = 0; purchases.raffleId = unitRaffleId; unitRafflePlayers[unitRaffleId].push(msg.sender); // Add user to raffle } // Store new ticket purchase if (purchases.numPurchases == purchases.ticketsBought.length) { purchases.ticketsBought.length += 1; } purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(unitRaffleTicketsBought, unitRaffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9) // Finally update ticket total unitRaffleTicketsBought += amount; } function startItemRaffle(uint256 endTime, uint256 rareId) external { require(msg.sender == owner); require(schema.validRareId(rareId)); require(rareItemOwner[rareId] == 0); require(block.timestamp < endTime); if (itemRaffleRareId != 0) { // Sanity to assure raffle has ended before next one starts require(itemRaffleWinner != 0); } // Reset previous raffle info itemRaffleWinningTicketSelected = false; itemRaffleTicketThatWon = 0; itemRaffleWinner = 0; itemRaffleTicketsBought = 0; // Set current raffle info itemRaffleEndTime = endTime; itemRaffleRareId = rareId; } function startUnitRaffle(uint256 endTime, uint256 unitId) external { require(msg.sender == owner); require(block.timestamp < endTime); if (unitRaffleRareId != 0) { // Sanity to assure raffle has ended before next one starts require(unitRaffleWinner != 0); } // Reset previous raffle info unitRaffleWinningTicketSelected = false; unitRaffleTicketThatWon = 0; unitRaffleWinner = 0; unitRaffleTicketsBought = 0; // Set current raffle info unitRaffleEndTime = endTime; unitRaffleRareId = unitId; unitRaffleId++; // Can't use unitRaffleRareId (as rare units are not unique) } function awardItemRafflePrize(address checkWinner, uint256 checkIndex) external { require(itemRaffleEndTime < block.timestamp); require(itemRaffleWinner == 0); require(rareItemOwner[itemRaffleRareId] == 0); if (!itemRaffleWinningTicketSelected) { drawRandomItemWinner(); // Ideally do it in one call (gas limit cautious) } // Reduce gas by (optionally) offering an address to _check_ for winner if (checkWinner != 0) { TicketPurchases storage tickets = rareItemTicketsBoughtByPlayer[checkWinner]; if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleId == itemRaffleRareId) { TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex]; if (itemRaffleTicketThatWon >= checkTicket.startId && itemRaffleTicketThatWon <= checkTicket.endId) { assignItemRafflePrize(checkWinner); // WINNER! return; } } } // Otherwise just naively try to find the winner (will work until mass amounts of players) for (uint256 i = 0; i < itemRafflePlayers[itemRaffleRareId].length; i++) { address player = itemRafflePlayers[itemRaffleRareId][i]; TicketPurchases storage playersTickets = rareItemTicketsBoughtByPlayer[player]; uint256 endIndex = playersTickets.numPurchases - 1; // Minor optimization to avoid checking every single player if (itemRaffleTicketThatWon >= playersTickets.ticketsBought[0].startId && itemRaffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) { for (uint256 j = 0; j < playersTickets.numPurchases; j++) { TicketPurchase storage playerTicket = playersTickets.ticketsBought[j]; if (itemRaffleTicketThatWon >= playerTicket.startId && itemRaffleTicketThatWon <= playerTicket.endId) { assignItemRafflePrize(player); // WINNER! return; } } } } } function awardUnitRafflePrize(address checkWinner, uint256 checkIndex) external { require(unitRaffleEndTime < block.timestamp); require(unitRaffleWinner == 0); if (!unitRaffleWinningTicketSelected) { drawRandomUnitWinner(); // Ideally do it in one call (gas limit cautious) } // Reduce gas by (optionally) offering an address to _check_ for winner if (checkWinner != 0) { TicketPurchases storage tickets = rareUnitTicketsBoughtByPlayer[checkWinner]; if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleId == unitRaffleId) { TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex]; if (unitRaffleTicketThatWon >= checkTicket.startId && unitRaffleTicketThatWon <= checkTicket.endId) { assignUnitRafflePrize(checkWinner); // WINNER! return; } } } // Otherwise just naively try to find the winner (will work until mass amounts of players) for (uint256 i = 0; i < unitRafflePlayers[unitRaffleId].length; i++) { address player = unitRafflePlayers[unitRaffleId][i]; TicketPurchases storage playersTickets = rareUnitTicketsBoughtByPlayer[player]; uint256 endIndex = playersTickets.numPurchases - 1; // Minor optimization to avoid checking every single player if (unitRaffleTicketThatWon >= playersTickets.ticketsBought[0].startId && unitRaffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) { for (uint256 j = 0; j < playersTickets.numPurchases; j++) { TicketPurchase storage playerTicket = playersTickets.ticketsBought[j]; if (unitRaffleTicketThatWon >= playerTicket.startId && unitRaffleTicketThatWon <= playerTicket.endId) { assignUnitRafflePrize(player); // WINNER! return; } } } } } function assignItemRafflePrize(address winner) internal { itemRaffleWinner = winner; rareItemOwner[itemRaffleRareId] = winner; rareItemPrice[itemRaffleRareId] = (schema.rareStartPrice(itemRaffleRareId) * 21) / 20; // Buy price slightly higher (Div pool cut) updatePlayersGoo(winner); uint256 upgradeClass; uint256 unitId; uint256 upgradeValue; (upgradeClass, unitId, upgradeValue) = schema.getRareInfo(itemRaffleRareId); upgradeUnitMultipliers(winner, upgradeClass, unitId, upgradeValue); } function assignUnitRafflePrize(address winner) internal { unitRaffleWinner = winner; updatePlayersGoo(winner); increasePlayersGooProduction(winner, getUnitsProduction(winner, unitRaffleRareId, 1)); unitsOwned[winner][unitRaffleRareId] += 1; } // Random enough for small contests (Owner only to prevent trial & error execution) function drawRandomItemWinner() public { require(msg.sender == owner); require(itemRaffleEndTime < block.timestamp); require(!itemRaffleWinningTicketSelected); uint256 seed = itemRaffleTicketsBought + block.timestamp; itemRaffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, itemRaffleTicketsBought); itemRaffleWinningTicketSelected = true; } function drawRandomUnitWinner() public { require(msg.sender == owner); require(unitRaffleEndTime < block.timestamp); require(!unitRaffleWinningTicketSelected); uint256 seed = unitRaffleTicketsBought + block.timestamp; unitRaffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, unitRaffleTicketsBought); unitRaffleWinningTicketSelected = true; } // Gives players the upgrades they 'previously paid for' (i.e. will be one of same unit/type/value of their v1 purchase) // Tx of their (prior) purchase is provided so can be validated by anyone for 0 abuse function migrateV1Upgrades(address[] playerToCredit, uint256[] upgradeIds, uint256[] txProof) external { require(msg.sender == owner); require(!gameStarted); // Pre-game migration for (uint256 i = 0; i < txProof.length; i++) { address player = playerToCredit[i]; uint256 upgradeId = upgradeIds[i]; uint256 unitId = schema.upgradeUnitId(upgradeId); if (unitId > 0 && !upgradesOwned[player][upgradeId]) { // Upgrade valid (and haven't already migrated) uint256 upgradeClass = schema.upgradeClass(upgradeId); uint256 upgradeValue = schema.upgradeValue(upgradeId); upgradeUnitMultipliers(player, upgradeClass, unitId, upgradeValue); upgradesOwned[player][upgradeId] = true; emit UpgradeMigration(player, upgradeId, txProof[i]); } } } function protectAddress(address exchange, bool shouldProtect) external { require(msg.sender == owner); if (shouldProtect) { require(getGooProduction(exchange) == 0); // Can't protect actual players } protectedAddresses[exchange] = shouldProtect; } function attackPlayer(address target) external { require(battleCooldown[msg.sender] < block.timestamp); require(target != msg.sender); require(!protectedAddresses[target]); // Target not whitelisted (i.e. exchange wallets) uint256 attackingPower; uint256 defendingPower; uint256 stealingPower; (attackingPower, defendingPower, stealingPower) = getPlayersBattlePower(msg.sender, target); if (battleCooldown[target] > block.timestamp) { // When on battle cooldown you're vulnerable (starting value is 50% normal power) defendingPower = schema.getWeakenedDefensePower(defendingPower); } if (attackingPower > defendingPower) { battleCooldown[msg.sender] = block.timestamp + 30 minutes; if (balanceOf(target) > stealingPower) { // Save all their unclaimed goo, then steal attacker's max capacity (at same time) uint256 unclaimedGoo = balanceOfUnclaimedGoo(target); if (stealingPower > unclaimedGoo) { uint256 gooDecrease = stealingPower - unclaimedGoo; gooBalance[target] -= gooDecrease; roughSupply -= gooDecrease; } else { uint256 gooGain = unclaimedGoo - stealingPower; gooBalance[target] += gooGain; roughSupply += gooGain; } gooBalance[msg.sender] += stealingPower; emit PlayerAttacked(msg.sender, target, true, stealingPower); } else { emit PlayerAttacked(msg.sender, target, true, balanceOf(target)); gooBalance[msg.sender] += balanceOf(target); gooBalance[target] = 0; } lastGooSaveTime[target] = block.timestamp; // We don't need to claim/save msg.sender's goo (as production delta is unchanged) } else { battleCooldown[msg.sender] = block.timestamp + 10 minutes; emit PlayerAttacked(msg.sender, target, false, 0); } } function getPlayersBattlePower(address attacker, address defender) internal constant returns (uint256, uint256, uint256) { uint256 startId; uint256 endId; (startId, endId) = schema.battleUnitIdRange(); uint256 attackingPower; uint256 defendingPower; uint256 stealingPower; // Not ideal but will only be a small number of units (and saves gas when buying units) while (startId <= endId) { attackingPower += getUnitsAttack(attacker, startId, unitsOwned[attacker][startId]); stealingPower += getUnitsStealingCapacity(attacker, startId, unitsOwned[attacker][startId]); defendingPower += getUnitsDefense(defender, startId, unitsOwned[defender][startId]); startId++; } return (attackingPower, defendingPower, stealingPower); } function getPlayersBattleStats(address player) external constant returns (uint256, uint256, uint256, uint256) { uint256 startId; uint256 endId; (startId, endId) = schema.battleUnitIdRange(); uint256 attackingPower; uint256 defendingPower; uint256 stealingPower; // Not ideal but will only be a small number of units (and saves gas when buying units) while (startId <= endId) { attackingPower += getUnitsAttack(player, startId, unitsOwned[player][startId]); stealingPower += getUnitsStealingCapacity(player, startId, unitsOwned[player][startId]); defendingPower += getUnitsDefense(player, startId, unitsOwned[player][startId]); startId++; } if (battleCooldown[player] > block.timestamp) { // When on battle cooldown you're vulnerable (starting value is 50% normal power) defendingPower = schema.getWeakenedDefensePower(defendingPower); } return (attackingPower, defendingPower, stealingPower, battleCooldown[player]); } function getUnitsProduction(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) { return (amount * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]) * (10 + unitGooProductionMultiplier[player][unitId])); } function getUnitsAttack(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) { return (amount * (schema.unitAttack(unitId) + unitAttackIncreases[player][unitId]) * (10 + unitAttackMultiplier[player][unitId])) / 10; } function getUnitsDefense(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) { return (amount * (schema.unitDefense(unitId) + unitDefenseIncreases[player][unitId]) * (10 + unitDefenseMultiplier[player][unitId])) / 10; } function getUnitsStealingCapacity(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) { return (amount * (schema.unitStealingCapacity(unitId) + unitGooStealingIncreases[player][unitId]) * (10 + unitGooStealingMultiplier[player][unitId])) / 10; } // To display on website function getGameInfo() external constant returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256[], bool[]){ uint256[] memory units = new uint256[](schema.currentNumberOfUnits()); bool[] memory upgrades = new bool[](schema.currentNumberOfUpgrades()); uint256 startId; uint256 endId; (startId, endId) = schema.productionUnitIdRange(); uint256 i; while (startId <= endId) { units[i] = unitsOwned[msg.sender][startId]; i++; startId++; } (startId, endId) = schema.battleUnitIdRange(); while (startId <= endId) { units[i] = unitsOwned[msg.sender][startId]; i++; startId++; } // Reset for upgrades i = 0; (startId, endId) = schema.upgradeIdRange(); while (startId <= endId) { upgrades[i] = upgradesOwned[msg.sender][startId]; i++; startId++; } return (block.timestamp, totalEtherGooResearchPool, totalGooProduction, totalGooDepositSnapshots[totalGooDepositSnapshots.length - 1], gooDepositSnapshots[msg.sender][totalGooDepositSnapshots.length - 1], nextSnapshotTime, balanceOf(msg.sender), ethBalance[msg.sender], getGooProduction(msg.sender), units, upgrades); } // To display on website function getRareItemInfo() external constant returns (address[], uint256[]) { address[] memory itemOwners = new address[](schema.currentNumberOfRares()); uint256[] memory itemPrices = new uint256[](schema.currentNumberOfRares()); uint256 startId; uint256 endId; (startId, endId) = schema.rareIdRange(); uint256 i; while (startId <= endId) { itemOwners[i] = rareItemOwner[startId]; itemPrices[i] = rareItemPrice[startId]; i++; startId++; } return (itemOwners, itemPrices); } // To display on website function viewUnclaimedResearchDividends() external constant returns (uint256, uint256, uint256) { uint256 startSnapshot = lastGooResearchFundClaim[msg.sender]; uint256 latestSnapshot = allocatedGooResearchSnapshots.length - 1; // No snapshots to begin with uint256 researchShare; uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xfffffffffffff] = 0; for (uint256 i = startSnapshot; i <= latestSnapshot; i++) { // Slightly complex things by accounting for days/snapshots when user made no tx's uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i]; bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i]; if (productionDuringSnapshot == 0 && !soldAllProduction) { productionDuringSnapshot = previousProduction; } else { previousProduction = productionDuringSnapshot; } researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i]; } return (researchShare, startSnapshot, latestSnapshot); } // To display on website function viewUnclaimedDepositDividends() external constant returns (uint256, uint256, uint256) { uint256 startSnapshot = lastGooDepositFundClaim[msg.sender]; uint256 latestSnapshot = allocatedGooDepositSnapshots.length - 1; // No snapshots to begin with uint256 depositShare; for (uint256 i = startSnapshot; i <= latestSnapshot; i++) { depositShare += (allocatedGooDepositSnapshots[i] * gooDepositSnapshots[msg.sender][i]) / totalGooDepositSnapshots[i]; } return (depositShare, startSnapshot, latestSnapshot); } // To allow clients to verify contestants function getItemRafflePlayers(uint256 raffleId) external constant returns (address[]) { return (itemRafflePlayers[raffleId]); } // To allow clients to verify contestants function getUnitRafflePlayers(uint256 raffleId) external constant returns (address[]) { return (unitRafflePlayers[raffleId]); } // To allow clients to verify contestants function getPlayersItemTickets(address player) external constant returns (uint256[], uint256[]) { TicketPurchases storage playersTickets = rareItemTicketsBoughtByPlayer[player]; if (playersTickets.raffleId == itemRaffleRareId) { uint256[] memory startIds = new uint256[](playersTickets.numPurchases); uint256[] memory endIds = new uint256[](playersTickets.numPurchases); for (uint256 i = 0; i < playersTickets.numPurchases; i++) { startIds[i] = playersTickets.ticketsBought[i].startId; endIds[i] = playersTickets.ticketsBought[i].endId; } } return (startIds, endIds); } // To allow clients to verify contestants function getPlayersUnitTickets(address player) external constant returns (uint256[], uint256[]) { TicketPurchases storage playersTickets = rareUnitTicketsBoughtByPlayer[player]; if (playersTickets.raffleId == unitRaffleId) { uint256[] memory startIds = new uint256[](playersTickets.numPurchases); uint256[] memory endIds = new uint256[](playersTickets.numPurchases); for (uint256 i = 0; i < playersTickets.numPurchases; i++) { startIds[i] = playersTickets.ticketsBought[i].startId; endIds[i] = playersTickets.ticketsBought[i].endId; } } return (startIds, endIds); } // To display on website function getLatestItemRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) { return (itemRaffleEndTime, itemRaffleRareId, itemRaffleTicketsBought, itemRaffleWinner, itemRaffleTicketThatWon); } // To display on website function getLatestUnitRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) { return (unitRaffleEndTime, unitRaffleRareId, unitRaffleTicketsBought, unitRaffleWinner, unitRaffleTicketThatWon); } // New units may be added in future, but check it matches existing schema so no-one can abuse selling. function updateGooConfig(address newSchemaAddress) external { require(msg.sender == owner); GooGameConfig newSchema = GooGameConfig(newSchemaAddress); requireExistingUnitsSame(newSchema); requireExistingUpgradesSame(newSchema); // Finally update config schema = GooGameConfig(newSchema); } function requireExistingUnitsSame(GooGameConfig newSchema) internal constant { // Requires units eth costs match up or fail execution uint256 startId; uint256 endId; (startId, endId) = schema.productionUnitIdRange(); while (startId <= endId) { require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId)); require(schema.unitGooProduction(startId) == newSchema.unitGooProduction(startId)); startId++; } (startId, endId) = schema.battleUnitIdRange(); while (startId <= endId) { require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId)); require(schema.unitAttack(startId) == newSchema.unitAttack(startId)); require(schema.unitDefense(startId) == newSchema.unitDefense(startId)); require(schema.unitStealingCapacity(startId) == newSchema.unitStealingCapacity(startId)); startId++; } } function requireExistingUpgradesSame(GooGameConfig newSchema) internal constant { uint256 startId; uint256 endId; // Requires ALL upgrade stats match up or fail execution (startId, endId) = schema.upgradeIdRange(); while (startId <= endId) { require(schema.upgradeGooCost(startId) == newSchema.upgradeGooCost(startId)); require(schema.upgradeEthCost(startId) == newSchema.upgradeEthCost(startId)); require(schema.upgradeClass(startId) == newSchema.upgradeClass(startId)); require(schema.upgradeUnitId(startId) == newSchema.upgradeUnitId(startId)); require(schema.upgradeValue(startId) == newSchema.upgradeValue(startId)); startId++; } // Requires ALL rare stats match up or fail execution (startId, endId) = schema.rareIdRange(); while (startId <= endId) { uint256 oldClass; uint256 oldUnitId; uint256 oldValue; uint256 newClass; uint256 newUnitId; uint256 newValue; (oldClass, oldUnitId, oldValue) = schema.getRareInfo(startId); (newClass, newUnitId, newValue) = newSchema.getRareInfo(startId); require(oldClass == newClass); require(oldUnitId == newUnitId); require(oldValue == newValue); startId++; } } } contract GooGameConfig { mapping(uint256 => Unit) private unitInfo; mapping(uint256 => Upgrade) private upgradeInfo; mapping(uint256 => Rare) private rareInfo; uint256 public constant currentNumberOfUnits = 15; uint256 public constant currentNumberOfUpgrades = 210; uint256 public constant currentNumberOfRares = 2; address public owner; struct Unit { uint256 unitId; uint256 baseGooCost; uint256 gooCostIncreaseHalf; // Halfed to make maths slightly less (cancels a 2 out) uint256 ethCost; uint256 baseGooProduction; uint256 attackValue; uint256 defenseValue; uint256 gooStealingCapacity; bool unitSellable; // Rare units (from raffle) not sellable } struct Upgrade { uint256 upgradeId; uint256 gooCost; uint256 ethCost; uint256 upgradeClass; uint256 unitId; uint256 upgradeValue; uint256 prerequisiteUpgrade; } struct Rare { uint256 rareId; uint256 ethCost; uint256 rareClass; uint256 unitId; uint256 rareValue; } function GooGameConfig() public { owner = msg.sender; rareInfo[1] = Rare(1, 0.5 ether, 1, 1, 40); // 40 = +400% rareInfo[2] = Rare(2, 0.5 ether, 0, 2, 35); // +35 unitInfo[1] = Unit(1, 0, 10, 0, 2, 0, 0, 0, true); unitInfo[2] = Unit(2, 100, 50, 0, 5, 0, 0, 0, true); unitInfo[3] = Unit(3, 0, 0, 0.01 ether, 100, 0, 0, 0, true); unitInfo[4] = Unit(4, 200, 100, 0, 10, 0, 0, 0, true); unitInfo[5] = Unit(5, 500, 250, 0, 20, 0, 0, 0, true); unitInfo[6] = Unit(6, 1000, 500, 0, 40, 0, 0, 0, true); unitInfo[7] = Unit(7, 0, 1000, 0.05 ether, 500, 0, 0, 0, true); unitInfo[8] = Unit(8, 1500, 750, 0, 60, 0, 0, 0, true); unitInfo[9] = Unit(9, 0, 0, 10 ether, 6000, 0, 0, 0, false); // First secret rare unit from raffle (unsellable) unitInfo[40] = Unit(40, 50, 25, 0, 0, 10, 10, 10000, true); unitInfo[41] = Unit(41, 100, 50, 0, 0, 1, 25, 500, true); unitInfo[42] = Unit(42, 0, 0, 0.01 ether, 0, 200, 10, 50000, true); unitInfo[43] = Unit(43, 250, 125, 0, 0, 25, 1, 15000, true); unitInfo[44] = Unit(44, 500, 250, 0, 0, 20, 40, 5000, true); unitInfo[45] = Unit(45, 0, 2500, 0.02 ether, 0, 0, 0, 100000, true); } address allowedConfig; function setConfigSetupContract(address schema) external { require(msg.sender == owner); allowedConfig = schema; } function addUpgrade(uint256 id, uint256 goo, uint256 eth, uint256 class, uint256 unit, uint256 value, uint256 prereq) external { require(msg.sender == allowedConfig); upgradeInfo[id] = Upgrade(id, goo, eth, class, unit, value, prereq); } function getGooCostForUnit(uint256 unitId, uint256 existing, uint256 amount) public constant returns (uint256) { Unit storage unit = unitInfo[unitId]; if (amount == 1) { // 1 if (existing == 0) { return unit.baseGooCost; } else { return unit.baseGooCost + (existing * unit.gooCostIncreaseHalf * 2); } } else if (amount > 1) { uint256 existingCost; if (existing > 0) { // Gated by unit limit existingCost = (unit.baseGooCost * existing) + (existing * (existing - 1) * unit.gooCostIncreaseHalf); } existing = SafeMath.add(existing, amount); return SafeMath.add(SafeMath.mul(unit.baseGooCost, existing), SafeMath.mul(SafeMath.mul(existing, (existing - 1)), unit.gooCostIncreaseHalf)) - existingCost; } } function getWeakenedDefensePower(uint256 defendingPower) external constant returns (uint256) { return defendingPower / 2; } function validRareId(uint256 rareId) external constant returns (bool) { return (rareId > 0 && rareId < 3); } function unitSellable(uint256 unitId) external constant returns (bool) { return unitInfo[unitId].unitSellable; } function unitEthCost(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].ethCost; } function unitGooProduction(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].baseGooProduction; } function unitAttack(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].attackValue; } function unitDefense(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].defenseValue; } function unitStealingCapacity(uint256 unitId) external constant returns (uint256) { return unitInfo[unitId].gooStealingCapacity; } function rareStartPrice(uint256 rareId) external constant returns (uint256) { return rareInfo[rareId].ethCost; } function upgradeGooCost(uint256 upgradeId) external constant returns (uint256) { return upgradeInfo[upgradeId].gooCost; } function upgradeEthCost(uint256 upgradeId) external constant returns (uint256) { return upgradeInfo[upgradeId].ethCost; } function upgradeClass(uint256 upgradeId) external constant returns (uint256) { return upgradeInfo[upgradeId].upgradeClass; } function upgradeUnitId(uint256 upgradeId) external constant returns (uint256) { return upgradeInfo[upgradeId].unitId; } function upgradeValue(uint256 upgradeId) external constant returns (uint256) { return upgradeInfo[upgradeId].upgradeValue; } function productionUnitIdRange() external constant returns (uint256, uint256) { return (1, 9); } function battleUnitIdRange() external constant returns (uint256, uint256) { return (40, 45); } function upgradeIdRange() external constant returns (uint256, uint256) { return (1, 210); } function rareIdRange() external constant returns (uint256, uint256) { return (1, 2); } function getUpgradeInfo(uint256 upgradeId) external constant returns (uint256, uint256, uint256, uint256, uint256, uint256) { return (upgradeInfo[upgradeId].gooCost, upgradeInfo[upgradeId].ethCost, upgradeInfo[upgradeId].upgradeClass, upgradeInfo[upgradeId].unitId, upgradeInfo[upgradeId].upgradeValue, upgradeInfo[upgradeId].prerequisiteUpgrade); } function getRareInfo(uint256 rareId) external constant returns (uint256, uint256, uint256) { return (rareInfo[rareId].rareClass, rareInfo[rareId].unitId, rareInfo[rareId].rareValue); } function getUnitInfo(uint256 unitId, uint256 existing, uint256 amount) external constant returns (uint256, uint256, uint256, uint256) { return (unitInfo[unitId].unitId, unitInfo[unitId].baseGooProduction, getGooCostForUnit(unitId, existing, amount), SafeMath.mul(unitInfo[unitId].ethCost, amount)); } } 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; } }
Target not whitelisted (i.e. exchange wallets)
require(!protectedAddresses[target]);
1,496,744
[ 1, 2326, 486, 26944, 261, 77, 18, 73, 18, 7829, 17662, 2413, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 5, 1117, 7148, 63, 3299, 19226, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; import "./URLResolver.sol"; /** @title A resolver contract that can be used for a single merchant with many products */ contract StandardResolver is URLResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; // bytes4(keccak256("supportsInterface(bytes4)")) bytes4 constant PRODUCT_URL_INTERFACE_ID = 0xaf655719; // bytes4(keccak256("productURL(uint256)")) string url; address public owner; modifier only_owner { require(owner == msg.sender); _; } function StandardResolver(address _owner, string _productURL) public { owner = _owner; url = _productURL; } function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == INTERFACE_META_ID || interfaceID == PRODUCT_URL_INTERFACE_ID; } function productURL(uint256 DIN) public view returns (string) { return url; } function setProductURL(string _productURL) public only_owner { url = _productURL; } function setOwner(address _owner) public only_owner { owner = _owner; } }
bytes4(keccak256("supportsInterface(bytes4)"))
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
13,097,719
[ 1, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 28064, 1358, 12, 3890, 24, 2225, 3719, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1731, 24, 5381, 11391, 11300, 67, 19294, 67, 734, 273, 374, 92, 1611, 1403, 71, 29, 69, 27, 31, 1850, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xA209aA89681195CEbF6DbB79c544061649B003d3/sources/DexRunner.sol
If user withdraw within 1 month from first deposit, they dont receive reward.That reward will be use to distribute to others
stakeRewardSupply = stakeRewardSupply.add(pendingToken);
2,971,558
[ 1, 2047, 729, 598, 9446, 3470, 404, 3138, 628, 1122, 443, 1724, 16, 2898, 14046, 6798, 19890, 18, 18163, 19890, 903, 506, 999, 358, 25722, 358, 10654, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 384, 911, 17631, 1060, 3088, 1283, 273, 384, 911, 17631, 1060, 3088, 1283, 18, 1289, 12, 9561, 1345, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7700/0xCCaeCEDeD554e1e1cE31e6B703e67E456E7f2b7B/sources/contracts/manifold/overrides/RoyaltyOverrideFactoryOnDefaultInit.sol
If the caller does not have authorisation (e.g. not owner of NFT collection) they should use this and contact Alto.build
function createOverrideDefaultOnInitUnlinked( uint16 royaltyNumberator, address royaltyReceiver ) public returns (address) { IEIP2981RoyaltyOverride.TokenRoyalty memory royaltyInfo = IEIP2981RoyaltyOverride.TokenRoyalty( royaltyReceiver, royaltyNumberator ); address clone = Clones.clone(originAddress); EIP2981RoyaltyOverrideCloneable(clone).initialize(); EIP2981RoyaltyOverrideCloneable(clone).setDefaultRoyalty(royaltyInfo); EIP2981RoyaltyOverrideCloneable(clone).transferOwnership(msg.sender); emit EIP2981RoyaltyOverrideCreated(clone); return clone; }
4,659,280
[ 1, 2047, 326, 4894, 1552, 486, 1240, 2869, 10742, 261, 73, 18, 75, 18, 486, 3410, 434, 423, 4464, 1849, 13, 2898, 1410, 999, 333, 471, 5388, 2262, 869, 18, 3510, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 752, 6618, 1868, 1398, 2570, 984, 17738, 12, 203, 565, 2254, 2313, 721, 93, 15006, 1854, 639, 16, 203, 565, 1758, 721, 93, 15006, 12952, 203, 225, 262, 1071, 1135, 261, 2867, 13, 288, 203, 1377, 10897, 2579, 5540, 11861, 54, 13372, 15006, 6618, 18, 1345, 54, 13372, 15006, 3778, 721, 93, 15006, 966, 273, 10897, 2579, 5540, 11861, 54, 13372, 15006, 6618, 18, 1345, 54, 13372, 15006, 12, 203, 3639, 721, 93, 15006, 12952, 16, 203, 3639, 721, 93, 15006, 1854, 639, 203, 1377, 11272, 203, 203, 1377, 1758, 3236, 273, 3905, 5322, 18, 14056, 12, 10012, 1887, 1769, 203, 1377, 512, 2579, 5540, 11861, 54, 13372, 15006, 6618, 10930, 429, 12, 14056, 2934, 11160, 5621, 203, 1377, 512, 2579, 5540, 11861, 54, 13372, 15006, 6618, 10930, 429, 12, 14056, 2934, 542, 1868, 54, 13372, 15006, 12, 3800, 15006, 966, 1769, 203, 1377, 512, 2579, 5540, 11861, 54, 13372, 15006, 6618, 10930, 429, 12, 14056, 2934, 13866, 5460, 12565, 12, 3576, 18, 15330, 1769, 203, 1377, 3626, 512, 2579, 5540, 11861, 54, 13372, 15006, 6618, 6119, 12, 14056, 1769, 203, 203, 1377, 327, 3236, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x91ECB2ffcEA991B47052429393B6901C0A8A1CFD/sources/contracts/staker/BorrowStaker.sol
@notice Same as the `claim_rewards` function above
function claimRewards(address from) external returns (uint256[] memory) { return claim_rewards(from); }
3,195,164
[ 1, 8650, 487, 326, 1375, 14784, 67, 266, 6397, 68, 445, 5721, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7516, 17631, 14727, 12, 2867, 628, 13, 3903, 1135, 261, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 327, 7516, 67, 266, 6397, 12, 2080, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // 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; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value);
1,018,830
[ 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, 9349, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 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 ]
pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // 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. // // ---------------------------------------------------------------------------- // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- /* Origin chain | Auxiliary chain ------------------------------------------------------------------------------- EIP20Gateway - - - - - - - - - - -EIP20CoGateway ------------------------------------------------------------------------------- 1. Redeem and Unstake: Normal flow confirmRedeemIntent <--- redeem | progressUnstake (HL) ---> progressRedeem (HL) ------------------------------------------------------------------------------- 2. Redeem and Unstake (Revert): Normal flow confirmRedeemIntent <--- redeem | confirmRevertRedeemIntent <--- revertRedeem | progressRevertRedeem ---> progressRevertRedeem ------------------------------------------------------------------------------- 3. Redeem and Unstake: Incase the facilitator is not able to progress confirmRedeemIntent <--- redeem (by facilitator) (by facilitator) | facilitator (offline) | progressUnstakeWithProof <--- progressRedeemWithProof ------------------------------------------------------------------------------- */ import "./UtilityTokenInterface.sol"; import "./GatewayBase.sol"; import "../lib/OrganizationInterface.sol"; /** * @title EIP20CoGateway Contract * * @notice EIP20CoGateway act as medium to send messages from auxiliary * chain to origin chain. Currently CoGateway supports redeem and * unstake and revert redeem message */ contract EIP20CoGateway is GatewayBase { /* Events */ /** Emitted whenever a stake intent is confirmed. */ event StakeIntentConfirmed( bytes32 indexed _messageHash, address _staker, uint256 _stakerNonce, address _beneficiary, uint256 _amount, uint256 _blockHeight, bytes32 _hashLock ); /** Emitted whenever a utility tokens are minted. */ event MintProgressed( bytes32 indexed _messageHash, address _staker, address _beneficiary, uint256 _stakeAmount, uint256 _mintedAmount, uint256 _rewardAmount, bool _proofProgress, bytes32 _unlockSecret ); /** Emitted whenever revert stake intent is confirmed. */ event RevertStakeIntentConfirmed( bytes32 indexed _messageHash, address _staker, uint256 _stakerNonce, uint256 _amount ); /** Emitted whenever a stake intent is reverted. */ event RevertStakeProgressed( bytes32 indexed _messageHash, address _staker, uint256 _stakerNonce, uint256 _amount ); /** Emitted whenever redeem is initiated. */ event RedeemIntentDeclared( bytes32 indexed _messageHash, address _redeemer, uint256 _redeemerNonce, address _beneficiary, uint256 _amount ); /** Emitted whenever redeem is completed. */ event RedeemProgressed( bytes32 indexed _messageHash, address _redeemer, uint256 _redeemerNonce, uint256 _amount, bool _proofProgress, bytes32 _unlockSecret ); /** Emitted whenever revert redeem is initiated. */ event RevertRedeemDeclared( bytes32 indexed _messageHash, address _redeemer, uint256 _redeemerNonce, uint256 _amount ); /** Emitted whenever revert redeem is complete. */ event RedeemReverted( bytes32 indexed _messageHash, address _redeemer, uint256 _redeemerNonce, uint256 _amount ); /* Struct */ /** * Redeem stores the redeem information, beneficiary address, message data * and facilitator address. */ struct Redeem { /** Amount that will be redeemed. */ uint256 amount; /** * Address where the value tokens will be unstaked in the origin * chain. */ address beneficiary; /** Bounty amount kept by facilitator for transferring redeem messages. */ uint256 bounty; } /** * Mint stores the minting information like mint amount, * beneficiary address, message data. */ struct Mint { /** Amount that will be minted. */ uint256 amount; /** Address for which the utility tokens will be minted */ address payable beneficiary; } /* Public Variables */ /** Address of utility token. */ address public utilityToken; /** Address of value token. */ address public valueToken; /** Address where token will be burned. */ address payable public burner; /** Maps messageHash to the Mint object. */ mapping(bytes32 => Mint) public mints; /** Maps messageHash to the Redeem object. */ mapping(bytes32 => Redeem) public redeems; /* Constructor */ /** * @notice Initialize the contract by providing the Gateway contract * address for which the CoGateway will enable facilitation of * mint and redeem. * * @param _valueToken The value token contract address. * @param _utilityToken The utility token address that will be used for * minting the utility token. * @param _stateRootProvider Contract address which implements * StateRootInterface. * @param _bounty The amount that facilitator stakes to initiate the stake * process. * @param _organization Address of an organization contract. * @param _gateway Gateway contract address. * @param _burner Address where tokens will be burned. */ constructor( address _valueToken, address _utilityToken, StateRootInterface _stateRootProvider, uint256 _bounty, OrganizationInterface _organization, address _gateway, address payable _burner ) GatewayBase( _stateRootProvider, _bounty, _organization ) public { require( _valueToken != address(0), "Value token address must not be zero." ); require( _utilityToken != address(0), "Utility token address must not be zero." ); require( _gateway != address(0), "Gateway address must not be zero." ); valueToken = _valueToken; utilityToken = _utilityToken; remoteGateway = _gateway; burner = _burner; // Update the encodedGatewayPath. encodedGatewayPath = BytesLib.bytes32ToBytes( keccak256(abi.encodePacked(remoteGateway)) ); } /* External functions */ /** * @notice Complete mint process by minting the utility tokens. * * @param _messageHash Message hash. * @param _unlockSecret Unlock secret for the hashLock provided by the * facilitator while initiating the stake. * * @return beneficiary_ Address to which the utility tokens will be * transferred after minting. * @return stakeAmount_ Total amount for which the stake was * initiated. The reward amount is deducted from the * this amount and is given to the facilitator. * @return mintedAmount_ Actual minted amount, after deducting the reward * from the total (stake) amount. * @return rewardAmount_ Reward amount that is transferred to facilitator. */ function progressMint( bytes32 _messageHash, bytes32 _unlockSecret ) external returns ( address beneficiary_, uint256 stakeAmount_, uint256 mintedAmount_, uint256 rewardAmount_ ) { // Get the initial gas amount. uint256 initialGas = gasleft(); require( _messageHash != bytes32(0), "Message hash must not be zero." ); MessageBus.Message storage message = messages[_messageHash]; // Progress inbox. MessageBus.progressInbox( messageBox, message, _unlockSecret ); (beneficiary_, stakeAmount_, mintedAmount_, rewardAmount_) = progressMintInternal(_messageHash, initialGas, false, _unlockSecret, message); } /** * @notice Completes the mint process by providing the merkle proof * instead of unlockSecret. In case the facilitator process is not * able to complete the stake and mint process then this is an * alternative approach to complete the process. * * @dev This can be called to prove that the outbox status of messageBox on * Gateway is either declared or progressed. * * @param _messageHash Message hash. * @param _rlpParentNodes RLP encoded storage proof of the messageBox inbox * in the Gateway. * * @param _blockHeight Block number for which the proof is valid. * @param _messageStatus Message status i.e. Declared or Progressed that * will be proved. * * @return beneficiary_ Address to which the utility tokens will be * transferred after minting. * @return stakeAmount_ Total amount for which the stake was initiated. The * reward amount is deducted from the total amount and * is given to the facilitator. * @return mintedAmount_ Actual minted amount, after deducting the reward * from the total amount. * @return rewardAmount_ Reward amount that is transferred to facilitator. */ function progressMintWithProof( bytes32 _messageHash, bytes memory _rlpParentNodes, uint256 _blockHeight, uint256 _messageStatus ) public returns ( address beneficiary_, uint256 stakeAmount_, uint256 mintedAmount_, uint256 rewardAmount_ ) { // Get the inital gas. uint256 initialGas = gasleft(); require( _messageHash != bytes32(0), "Message hash must not be zero." ); require( _rlpParentNodes.length > 0, "RLP parent nodes must not be zero." ); // Get the storage root for the given block height. bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero." ); MessageBus.Message storage message = messages[_messageHash]; MessageBus.progressInboxWithProof( messageBox, message, _rlpParentNodes, MESSAGE_BOX_OFFSET, storageRoot, MessageBus.MessageStatus(_messageStatus) ); (beneficiary_, stakeAmount_, mintedAmount_, rewardAmount_) = progressMintInternal(_messageHash, initialGas, true, bytes32(0), message); } /** * @notice Declare stake revert intent. This will set message status to * revoked. This method will also clear mint mapping storage. * * @param _messageHash Message hash. * @param _blockHeight Block number for which the proof is valid * @param _rlpParentNodes RLP encoded parent node data to prove * DeclaredRevocation in messageBox outbox of * Gateway. * * @return staker_ Staker address * @return stakerNonce_ Staker nonce * @return amount_ Redeem amount */ function confirmRevertStakeIntent( bytes32 _messageHash, uint256 _blockHeight, bytes calldata _rlpParentNodes ) external returns ( address staker_, uint256 stakerNonce_, uint256 amount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero." ); require( _rlpParentNodes.length > 0, "RLP parent nodes must not be zero." ); amount_ = mints[_messageHash].amount; require( amount_ > uint256(0), "Mint amount must not be zero." ); delete mints[_messageHash]; MessageBus.Message storage message = messages[_messageHash]; require( message.intentHash != bytes32(0), "Stake intent hash must not be zero." ); // Get the storage root. bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero." ); // Confirm revocation. MessageBus.confirmRevocation( messageBox, message, _rlpParentNodes, MESSAGE_BOX_OFFSET, storageRoot ); staker_ = message.sender; stakerNonce_ = message.nonce; emit RevertStakeIntentConfirmed( _messageHash, message.sender, message.nonce, amount_ ); } /** * @notice Completes the redeem process. This decreases token supply * on successful redeem. * * @dev Message bus ensures correct execution sequence of methods and also * provides safety mechanism for any possible re-entrancy attack. * * @param _messageHash Message hash for redeem message. * @param _unlockSecret Unlock secret for the hashLock provide by the * facilitator while initiating the redeem. * * @return redeemer_ Redeemer address. * @return redeemAmount_ Redeem amount. */ function progressRedeem( bytes32 _messageHash, bytes32 _unlockSecret ) external returns ( address redeemer_, uint256 redeemAmount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero." ); MessageBus.Message storage message = messages[_messageHash]; // Get the redeemer address. redeemer_ = message.sender; redeemAmount_ = redeems[_messageHash].amount; MessageBus.progressOutbox( messageBox, message, _unlockSecret ); (redeemer_, redeemAmount_) = progressRedeemInternal(_messageHash, message, false, _unlockSecret); } /** * @notice Completes the redeem process by providing the merkle proof * instead of unlockSecret. In case the facilitator process is not * able to complete the redeem and unstake process then this is an * alternative approach to complete the process * * @dev This can be called to prove that the inbox status of messageBox on * Gateway is either declared or progressed. * * @param _messageHash Message hash. * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox of Gateway * @param _blockHeight Block number for which the proof is valid * @param _messageStatus Message status i.e. Declared or Progressed that * will be proved. * * @return redeemer_ Redeemer address * @return redeemAmount_ Redeem amount */ function progressRedeemWithProof( bytes32 _messageHash, bytes calldata _rlpParentNodes, uint256 _blockHeight, uint256 _messageStatus ) external returns ( address redeemer_, uint256 redeemAmount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero." ); require( _rlpParentNodes.length > 0, "RLP parent nodes must not be zero." ); bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero." ); MessageBus.Message storage message = messages[_messageHash]; MessageBus.progressOutboxWithProof( messageBox, message, _rlpParentNodes, MESSAGE_BOX_OFFSET, storageRoot, MessageBus.MessageStatus(_messageStatus) ); (redeemer_, redeemAmount_) = progressRedeemInternal(_messageHash, message, true, bytes32(0)); } /** * @notice Revert the redeem process. Only redeemer can * revert redeem by providing penalty i.e. 1.5 times of * bounty amount. On revert process, penalty and facilitator * bounty will be burned. * * @param _messageHash Message hash. * * @return redeemer_ Redeemer address * @return redeemerNonce_ Redeemer nonce * @return amount_ Redeem amount */ function revertRedeem( bytes32 _messageHash ) payable external returns ( address redeemer_, uint256 redeemerNonce_, uint256 amount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero." ); // Get the message object for the _messageHash. MessageBus.Message storage message = messages[_messageHash]; require( message.sender == msg.sender, "Only redeemer can revert redeem." ); // Penalty charged to redeemer. uint256 penalty = penaltyFromBounty(redeems[_messageHash].bounty); require( msg.value == penalty, "msg.value must match the penalty amount." ); // Declare redeem revocation. MessageBus.declareRevocationMessage( messageBox, message ); redeemer_ = message.sender; redeemerNonce_ = message.nonce; amount_ = redeems[_messageHash].amount; // Burn penalty amount. Reentrancy is protected by message bus states. burner.transfer(penalty); emit RevertRedeemDeclared( _messageHash, redeemer_, redeemerNonce_, amount_ ); } /** * @notice Complete revert redeem by providing the merkle proof. * It will burn facilitator bounty. * * @dev Message bus ensures correct execution sequence of methods and also * provides safety mechanism for any possible re-entrancy attack. * * @param _messageHash Message hash. * @param _blockHeight Block number for which the proof is valid * @param _rlpParentNodes RLP encoded storage proof to prove * DeclaredRevocation in messageBox inbox of Gateway. * * @return redeemer_ Redeemer address * @return redeemerNonce_ Redeemer nonce * @return amount_ Redeem amount */ function progressRevertRedeem( bytes32 _messageHash, uint256 _blockHeight, bytes calldata _rlpParentNodes ) external returns ( address redeemer_, uint256 redeemerNonce_, uint256 amount_ ) { require( _messageHash != bytes32(0), "Message hash must not be zero." ); require( _rlpParentNodes.length > 0, "RLP parent nodes must not be zero." ); // Get the message object. MessageBus.Message storage message = messages[_messageHash]; require( message.intentHash != bytes32(0), "RedeemIntentHash must not be zero." ); // Get the storageRoot for the given block height. bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero." ); Redeem storage redeemProcess = redeems[_messageHash]; redeemer_ = message.sender; redeemerNonce_ = message.nonce; amount_ = redeemProcess.amount; require( amount_ > 0, "Redeem request must exist." ); // Progress with revocation message. MessageBus.progressOutboxRevocation( messageBox, message, MESSAGE_BOX_OFFSET, _rlpParentNodes, storageRoot, MessageBus.MessageStatus.Revoked ); uint256 bounty = redeemProcess.bounty; // Delete the redeem data. delete redeems[_messageHash]; // Return the redeem amount back. EIP20Interface(utilityToken).transfer(message.sender, amount_); // Burn bounty. burner.transfer(bounty); emit RedeemReverted( _messageHash, message.sender, message.nonce, amount_ ); } /** * @notice Confirms the initiation of the stake process. * * @param _staker Staker address. * @param _stakerNonce Nonce of the staker address. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. This is payable so that it * provides flexibility of transferring base coin to account * on minting. * @param _amount Staked amount. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done * @param _gasLimit Gas limit that staker is ready to pay. * @param _hashLock Hash Lock provided by the facilitator. * @param _blockHeight Block number for which the proof is valid * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox of Gateway. * * @return messageHash_ which is unique for each request. */ function confirmStakeIntent( address _staker, uint256 _stakerNonce, address payable _beneficiary, uint256 _amount, uint256 _gasPrice, uint256 _gasLimit, bytes32 _hashLock, uint256 _blockHeight, bytes calldata _rlpParentNodes ) external returns (bytes32 messageHash_) { // Get the initial gas amount. uint256 initialGas = gasleft(); require( _staker != address(0), "Staker address must not be zero." ); require( _beneficiary != address(0), "Beneficiary address must not be zero." ); require( _amount != 0, "Stake amount must not be zero." ); require( _rlpParentNodes.length != 0, "RLP parent nodes must not be zero." ); require( UtilityTokenInterface(utilityToken).exists(_beneficiary), "Beneficiary address must exist." ); /* * Maximum reward possible is _gasPrice * _gasLimit, we check this * upfront in this function to make sure that after minting of the * tokens it is possible to give the reward to the facilitator. */ require( _amount > _gasPrice.mul(_gasLimit), "Maximum possible reward must be less than the stake amount." ); bytes32 intentHash = hashStakeIntent( _amount, _beneficiary ); MessageBus.Message memory message = MessageBus.Message( intentHash, _stakerNonce, _gasPrice, _gasLimit, _staker, _hashLock, 0 // Gas consumed will be updated at the end of this function. ); messageHash_ = storeMessage(message); registerInboxProcess( message.sender, message.nonce, messageHash_ ); // Create new mint object. mints[messageHash_] = Mint({ amount : _amount, beneficiary : _beneficiary }); /* * Execute the confirm stake intent. This is done in separate * function to avoid stack too deep error. */ confirmStakeIntentInternal( messages[messageHash_], _blockHeight, _rlpParentNodes ); // Emit StakeIntentConfirmed event. emit StakeIntentConfirmed( messageHash_, _staker, _stakerNonce, _beneficiary, _amount, _blockHeight, _hashLock ); // Update the gas consumed for this function. messages[messageHash_].gasConsumed = initialGas.sub(gasleft()); } /** * @notice Initiates the redeem process. * * @dev In order to redeem the redeemer needs to approve CoGateway contract * for redeem amount. Redeem amount is transferred from redeemer * address to CoGateway contract. * This is a payable function. The bounty is transferred in base coin. * Redeemer is always msg.sender. * * @param _amount Redeem amount that will be transferred from redeemer * account. * @param _beneficiary The address in the origin chain where the value * tok ens will be released. * @param _gasPrice Gas price that redeemer is ready to pay to get the * redeem process done. * @param _gasLimit Gas limit that redeemer is ready to pay. * @param _nonce Nonce of the redeemer address. * @param _hashLock Hash Lock provided by the facilitator. * * @return messageHash_ Unique for each request. */ function redeem( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, bytes32 _hashLock ) external payable returns (bytes32 messageHash_) { require( msg.value == bounty, "Payable amount should be equal to the bounty amount." ); require( _amount > uint256(0), "Redeem amount must not be zero." ); /* * Maximum reward possible is _gasPrice * _gasLimit, we check this * upfront in this function to make sure that after unstake of the * tokens it is possible to give the reward to the facilitator. */ require( _amount > _gasPrice.mul(_gasLimit), "Maximum possible reward must be less than the redeem amount." ); // Get the redeem intent hash. bytes32 intentHash = GatewayLib.hashRedeemIntent( _amount, _beneficiary, address(this) ); MessageBus.Message memory message = getMessage( intentHash, _nonce, _gasPrice, _gasLimit, msg.sender, _hashLock ); messageHash_ = storeMessage(message); registerOutboxProcess( msg.sender, _nonce, messageHash_ ); redeems[messageHash_] = Redeem({ amount : _amount, beneficiary : _beneficiary, bounty : bounty }); // Declare message in outbox. MessageBus.declareMessage( messageBox, messages[messageHash_] ); // Transfer redeem amount to Co-Gateway. EIP20Interface(utilityToken).transferFrom( msg.sender, address(this), _amount ); // Emit RedeemIntentDeclared event. emit RedeemIntentDeclared( messageHash_, msg.sender, _nonce, _beneficiary, _amount ); } /** * @notice Gets the penalty amount. If the message hash does not exist in * redeems mapping it will return zero amount. If the message is * already progressed or revoked then the penalty amount will be * zero. * * @param _messageHash Message hash. * * @return penalty_ Penalty amount. */ function penalty(bytes32 _messageHash) external view returns (uint256 penalty_) { penalty_ = super.penaltyFromBounty(redeems[_messageHash].bounty); } /* Private functions */ /** * @notice private function to execute confirm stake intent. * * @dev This function is to avoid stack too deep error in * confirmStakeIntent function * * @param _message message object * @param _blockHeight Block number for which the proof is valid * @param _rlpParentNodes RLP encoded parent nodes. * * @return `true` if executed successfully */ function confirmStakeIntentInternal( MessageBus.Message storage _message, uint256 _blockHeight, bytes memory _rlpParentNodes ) private returns (bool) { // Get storage root. bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root must not be zero" ); // Confirm message. MessageBus.confirmMessage( messageBox, _message, _rlpParentNodes, MESSAGE_BOX_OFFSET, storageRoot ); return true; } /** * @notice private function to calculate stake intent hash. * * @dev This function is to avoid stack too deep error in * confirmStakeIntent function * * @param _amount stake amount * @param _beneficiary minting account * * @return bytes32 stake intent hash */ function hashStakeIntent( uint256 _amount, address _beneficiary ) private view returns(bytes32) { return GatewayLib.hashStakeIntent( _amount, _beneficiary, remoteGateway ); } /** * @notice This is internal method for process minting contains common * logic. It doesn't mint reward if reward is 0. * * @dev Message bus ensures correct execution sequence of methods and also * provides safety mechanism for any possible re-entrancy attack. * * @param _messageHash Message hash. * @param _initialGas Initial gas during progress process. * * @param _proofProgress `true` if progress with proof, false if progress * with hashlock. * @param _unlockSecret Unlock secret to progress, zero in case of progress * with proof. * @param _message Message object. * * @return beneficiary_ Address to which the utility tokens will be * transferred after minting. * @return stakeAmount_ Total amount for which the stake was initiated. The * reward amount is deducted from the total amount and * is given to the facilitator. * @return mintedAmount_ Actual minted amount, after deducting the reward * from the total amount. * @return rewardAmount_ Reward amount that is transferred to facilitator. */ function progressMintInternal( bytes32 _messageHash, uint256 _initialGas, bool _proofProgress, bytes32 _unlockSecret, MessageBus.Message storage _message ) private returns ( address beneficiary_, uint256 stakeAmount_, uint256 mintedAmount_, uint256 rewardAmount_ ) { Mint storage mint = mints[_messageHash]; require( mint.amount > 0, "Mint request must exist." ); beneficiary_ = mint.beneficiary; address payable payableBeneficiary = mint.beneficiary; stakeAmount_ = mint.amount; (rewardAmount_, _message.gasConsumed) = feeAmount( _message.gasConsumed, _message.gasLimit, _message.gasPrice, _initialGas ); mintedAmount_ = stakeAmount_.sub(rewardAmount_); delete mints[_messageHash]; // Increase token supply with mint amount to beneficiary // after subtracting reward amount. UtilityTokenInterface(utilityToken).increaseSupply( payableBeneficiary, mintedAmount_ ); // Reward facilitator with the reward amount. UtilityTokenInterface(utilityToken).increaseSupply( msg.sender, rewardAmount_ ); // Emit MintProgressed event. emit MintProgressed( _messageHash, _message.sender, beneficiary_, stakeAmount_, mintedAmount_, rewardAmount_, _proofProgress, _unlockSecret ); } /** * @notice Internal method for progressRedeem. This is created to share * code between progressRedeem and progressRedeemWithProof. * * @param _messageHash Message hash of redeem message. * @param _message Message object. * @param _proofProgress True if progress with proof, false if progress * with hashlock. * @param _unlockSecret Unlock secret to progress, zero in case of progress * with proof. * * @return redeemer_ Redeemer address. * @return redeemAmount_ Redeem amount. */ function progressRedeemInternal( bytes32 _messageHash, MessageBus.Message storage _message, bool _proofProgress, bytes32 _unlockSecret ) private returns ( address redeemer_, uint256 redeemAmount_ ) { redeemAmount_ = redeems[_messageHash].amount; require( redeemAmount_ > 0, "Redeem request must exist." ); redeemer_ = _message.sender; uint256 stakedBounty = redeems[_messageHash].bounty; delete redeems[_messageHash]; // Decrease the token supply. UtilityTokenInterface(utilityToken).decreaseSupply(redeemAmount_); // Transfer the bounty amount to the facilitator. msg.sender.transfer(stakedBounty); emit RedeemProgressed( _messageHash, redeemer_, _message.nonce, redeemAmount_, _proofProgress, _unlockSecret ); } }
* Address where token will be burned. */
address payable public burner;
12,739,231
[ 1, 1887, 1625, 1147, 903, 506, 18305, 329, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1758, 8843, 429, 1071, 18305, 264, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract RajTest is owned { // Public variables of the token string public name = "RajTest"; string public symbol = "RT"; uint8 public decimals = 18; uint256 public totalSupply = 0; uint256 public buyPrice = 1045; bool public released = false; /// contract that is allowed to create new tokens and allows unlift the transfer limits on this token address public crowdsaleAgent; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function RajTest() public { } modifier canTransfer() { require(released); _; } modifier onlyCrowdsaleAgent() { require(msg.sender == crowdsaleAgent); _; } function releaseTokenTransfer() public onlyCrowdsaleAgent { released = true; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) canTransfer internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Check if sender is frozen require(!frozenAccount[_from]); // Check if recipient is frozen require(!frozenAccount[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyCrowdsaleAgent public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newBuyPrice) onlyOwner public { buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value * buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @dev Set the contract that can call release and make the token transferable. /// @param _crowdsaleAgent crowdsale contract address function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner public { crowdsaleAgent = _crowdsaleAgent; } }
@dev Set the contract that can call release and make the token transferable. @param _crowdsaleAgent crowdsale contract address
function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner public { crowdsaleAgent = _crowdsaleAgent; }
553,101
[ 1, 694, 326, 6835, 716, 848, 745, 3992, 471, 1221, 326, 1147, 7412, 429, 18, 225, 389, 71, 492, 2377, 5349, 3630, 276, 492, 2377, 5349, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11440, 492, 2377, 5349, 3630, 12, 2867, 389, 71, 492, 2377, 5349, 3630, 13, 1338, 5541, 1071, 288, 203, 3639, 276, 492, 2377, 5349, 3630, 273, 389, 71, 492, 2377, 5349, 3630, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; contract LeisureMeta is ERC20Burnable, Ownable, Pausable { LeisureMetaTimeLock public immutable daoPoolLock; uint256 private _dDay; event SetDDay(uint256 dDay); event SalesLock( address lock, address indexed beneficiary, uint256 totalAmount ); event GeneralLock( address lock, address indexed beneficiary, uint256 totalAmount ); constructor(address daopool, uint256 initialDDay) ERC20("LeisureMeta", "LM") { uint256 totalAmount = 5_000_000_000 * (10**uint256(decimals())); uint256 sixtyPercent = (totalAmount * 60) / 100; uint256 fortyPercent = (totalAmount * 40) / 100; _dDay = initialDDay; daoPoolLock = daoLock(daopool, sixtyPercent); _mint(_msgSender(), fortyPercent); } /** * @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"); } /** * @dev Set D-Day which might be the first day of listing in major crypto exchanges. */ function setDDay(uint256 dDay) external onlyOwner { require(dDay > block.timestamp, "D-Day must be in the future"); _dDay = dDay; emit SetDDay(_dDay); } function getDDay() external view returns (uint256) { return _dDay; } function daoLock(address beneficiary, uint256 amount) internal onlyOwner returns (LeisureMetaTimeLock) { uint256 aDay = 24 * 3600; uint256[] memory amounts = new uint256[](60); uint256[] memory releaseTimes = new uint256[](60); for (uint256 i = 0; i < 60; i++) { amounts[i] = amount / 60; releaseTimes[i] = 30 * aDay * (60 - i - 1); } LeisureMetaTimeLock lock = new LeisureMetaTimeLock( this, beneficiary, amounts, releaseTimes, false ); _mint(address(lock), amount); return lock; } function saleLock(address beneficiary, uint256 amount) external onlyOwner returns (LeisureMetaTimeLock) { uint256 aDay = 24 * 3600; uint256[] memory amounts = new uint256[](12); uint256[] memory releaseTimes = new uint256[](12); for (uint256 i = 0; i < 10; i++) { amounts[i] = amount / 10; releaseTimes[i] = 30 * aDay * (11 - i); } amounts[10] = (amount * 9) / 100; releaseTimes[10] = 30 * aDay; amounts[11] = amount / 100; releaseTimes[11] = 0; LeisureMetaTimeLock lock = _lock( beneficiary, amounts, releaseTimes, false ); emit SalesLock(address(lock), beneficiary, amount); return lock; } function generalLock(address beneficiary, uint256 amount) external onlyOwner returns (LeisureMetaTimeLock) { uint256 aDay = 24 * 3600; uint256[] memory amounts = new uint256[](20); uint256[] memory releaseTimes = new uint256[](20); for (uint256 i = 0; i < 20; i++) { amounts[i] = amount / 20; releaseTimes[i] = 30 * aDay * (25 - i); } LeisureMetaTimeLock lock = _lock( beneficiary, amounts, releaseTimes, true ); emit GeneralLock(address(lock), beneficiary, amount); return lock; } function _lock( address beneficiary_, uint256[] memory amounts_, uint256[] memory releaseTimes_, bool revocable_ ) internal onlyOwner returns (LeisureMetaTimeLock) { uint256 totalAmount = 0; for (uint256 i = 0; i < amounts_.length; i++) { totalAmount += amounts_[i]; } require(totalAmount <= balanceOf(_msgSender()), "insufficient balance"); LeisureMetaTimeLock item = new LeisureMetaTimeLock( this, beneficiary_, amounts_, releaseTimes_, revocable_ ); transfer(address(item), totalAmount); return item; } } contract LeisureMetaTimeLock is Context { using SafeERC20 for LeisureMeta; LeisureMeta public immutable LM; address public immutable beneficiary; bool public immutable revocable; uint256[] private _lockedAmounts; uint256[] private _releaseTimes; event Release( address indexed beneficiary, uint256 amount, uint256 releaseTime ); event Revoke(address indexed from, uint256 amount, uint256 revokeTime); /** * @dev Deploys a timelock instance that is able to hold the token specified, and will only release it to * `beneficiary_` when {release} is invoked after D-Day + `releaseTime_` (seconds). */ constructor( LeisureMeta lm_, address beneficiary_, uint256[] memory lockedAmounts_, uint256[] memory releaseTimes_, bool revocable_ ) { require( lockedAmounts_.length == releaseTimes_.length, "lockedAmounts and releaseTimes must be of the same length" ); require(beneficiary_ != address(0)); LM = lm_; beneficiary = beneficiary_; _lockedAmounts = lockedAmounts_; _releaseTimes = releaseTimes_; revocable = revocable_; } /** * @dev Returns the amount of a locked item. */ function lockedAmount(uint256 index) public view returns (uint256) { return _lockedAmounts[index]; } /** * @dev Returns the amount of a locked item. */ function releaseTime(uint256 index) public view returns (uint256) { return _releaseTimes[index]; } /** * @dev Returns the size of locked items. */ function numberOfLockedItems() public view returns (uint256) { return _lockedAmounts.length; } /** * @dev Transfers tokens held by the timelock to the beneficiary. * Will only succeed if invoked after the release time. */ function release() external { uint256 amount = 0; uint256 dday = LM.getDDay(); while ( numberOfLockedItems() > 0 && dday + releaseTime(numberOfLockedItems() - 1) < block.timestamp ) { amount += lockedAmount(numberOfLockedItems() - 1); _lockedAmounts.pop(); _releaseTimes.pop(); } require( amount <= LM.balanceOf(address(this)), "LeisureMetaTimelock: no tokens to release" ); emit Release(beneficiary, amount, block.timestamp); LM.safeTransfer(beneficiary, amount); } function revoke() external { require(revocable, "not revocable"); require(LM.owner() == _msgSender(), "only owner can revoke"); while (_lockedAmounts.length > 0) { _lockedAmounts.pop(); _releaseTimes.pop(); } uint256 amount = LM.balanceOf(address(this)); emit Revoke(beneficiary, amount, block.timestamp); LM.safeTransfer(_msgSender(), LM.balanceOf(address(this))); } } // 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 (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); } } } } // 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 (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 (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.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 { /** * @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 { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @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 (last updated v4.5.0) (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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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); } }
* @dev Set D-Day which might be the first day of listing in major crypto exchanges./
function setDDay(uint256 dDay) external onlyOwner { require(dDay > block.timestamp, "D-Day must be in the future"); _dDay = dDay; emit SetDDay(_dDay); }
14,728,455
[ 1, 694, 463, 17, 4245, 1492, 4825, 506, 326, 1122, 2548, 434, 11591, 316, 7888, 8170, 431, 6329, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 40, 4245, 12, 11890, 5034, 302, 4245, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 72, 4245, 405, 1203, 18, 5508, 16, 315, 40, 17, 4245, 1297, 506, 316, 326, 3563, 8863, 203, 3639, 389, 72, 4245, 273, 302, 4245, 31, 203, 3639, 3626, 1000, 40, 4245, 24899, 72, 4245, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; /// @title An Ownable Contract /// @author Mariona (seaona) /// @notice Do not use this contract on production contract Ownable { address private _owner; /// @dev Get current contract owner /// @return Address of current contract owner function getOwner() public view returns(address) { return _owner; } /// @dev Constructor that sets the _owner var to the creater of the contract constructor() { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /// @dev 'onlyOwner' modifier that throws if called by any account other than the owner. modifier onlyOwner { require(msg.sender == _owner, "You are not authorized to perform this action"); _; } /// @dev Transfers ownership to a new address, only owner can call this function /// @param newOwner The address of the new owner function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /// @dev Function for getting the contract owner /// @return Address with the current contract owner function getContractOwner() public view returns (address) { return _owner; } /// @dev Event that is throwed when contract ownership is transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); } /// @title A Pausable Contract /// @author Mariona (seaona) /// @notice Do not use this contract on production contract Pausable is Ownable { bool private _paused; /// @dev Pause contract when it's running function pauseContract() public onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } /// @dev Resume contract when it' not paused function resumeContract() public onlyOwner paused { _paused = false; emit ResumeContract(msg.sender); } /// @dev Constructor that sets the _paused variable to false constructor() { _paused = false; } /// @dev 'whenNotPaused' modifier that throws if contract is Paused. modifier whenNotPaused () { require(_paused == false, "Contract Paused!"); _; } /// @dev 'Paused' modifier that throws if contract is Not Paused. modifier paused() { require(_paused == true, "Contract not Paused!"); _; } /// @dev Function that returns if Contract is Paused /// @return Boolean saying if contract is Paused or not function isContractPaused() public view returns (bool) { return _paused; } /// @dev Paused event that emits the address that triggered the event /// @param account The address that triggered the event event Paused(address indexed account); /// @dev ResumeContract event that emits the address that triggered the event /// @param account The address that triggered the event event ResumeContract(address indexed account); }
@dev 'onlyOwner' modifier that throws if called by any account other than the owner.
modifier onlyOwner { require(msg.sender == _owner, "You are not authorized to perform this action"); _; }
1,823,403
[ 1, 11, 3700, 5541, 11, 9606, 716, 1216, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5541, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 389, 8443, 16, 315, 6225, 854, 486, 10799, 358, 3073, 333, 1301, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(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); _afterTokenTransfer(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 from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(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 {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: FTG_smart_contract.sol // Amended by [KAT]#1379 on discord pragma solidity >=0.7.0 <0.9.0; contract FTG is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = "ipfs://QmdKNGRWUKwJ46eVkFswDzqZ6etSFY55cycZyveupbKjk4/"; string public uriSuffix = ".json"; uint256 public cost = 0.05 ether; uint256 public maxSupply = 5000; uint256 public maxMintAmountPerTx = 10; bool public paused = false; constructor() ERC721("Free The Girls", "FTG") {} modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } 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" ); 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 setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } 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 withdraw() public onlyOwner { // This will transfer the remaining contract balance to the owner. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
File: FTG_smart_contract.sol Amended by [KAT]#1379 on discord
contract FTG is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriSuffix = ".json"; uint256 public cost = 0.05 ether; uint256 public maxSupply = 5000; uint256 public maxMintAmountPerTx = 10; bool public paused = false; constructor() ERC721("Free The Girls", "FTG") {} function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId } pragma solidity >=0.7.0 <0.9.0; modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } 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" ); 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 setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } 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 withdraw() public onlyOwner { require(os); } (bool os, ) = payable(owner()).call{value: address(this).balance}(""); function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
13,603,373
[ 1, 812, 30, 478, 56, 43, 67, 26416, 67, 16351, 18, 18281, 3986, 3934, 635, 306, 47, 789, 65, 3437, 7235, 603, 1015, 901, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 478, 56, 43, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 225, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 225, 9354, 87, 18, 4789, 3238, 14467, 31, 203, 203, 225, 533, 1071, 2003, 5791, 273, 3552, 1977, 14432, 203, 21281, 225, 2254, 5034, 1071, 6991, 273, 374, 18, 6260, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 943, 3088, 1283, 273, 20190, 31, 203, 225, 2254, 5034, 1071, 943, 49, 474, 6275, 2173, 4188, 273, 1728, 31, 203, 203, 225, 1426, 1071, 17781, 273, 629, 31, 203, 203, 203, 225, 3885, 1435, 4232, 39, 27, 5340, 2932, 9194, 1021, 611, 481, 3251, 3113, 315, 4464, 43, 7923, 2618, 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, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 411, 20, 18, 29, 18, 20, 31, 203, 203, 203, 203, 203, 225, 9606, 312, 474, 16687, 12, 11890, 5034, 389, 81, 474, 6275, 13, 288, 203, 565, 2583, 24899, 81, 474, 6275, 405, 374, 597, 389, 81, 474, 6275, 1648, 943, 49, 474, 6275, 2173, 4188, 16, 315, 1941, 312, 474, 3844, 4442, 1769, 203, 565, 2583, 12, 2859, 1283, 18, 2972, 1435, 2 ]
./full_match/1/0x3AdAE9699029AB2953F607AE1f62372681D35978/sources/contracts/AvoFactoryProxy.sol
@title AvoFactoryProxy @notice Default ERC1967Proxy for AvoFactory
contract AvoFactoryProxy is TransparentUpgradeableProxy { constructor( address logic_, address admin_, bytes memory data_ pragma solidity >=0.8.17; import { TransparentUpgradeableProxy } from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; ) payable TransparentUpgradeableProxy(logic_, admin_, data_) {} }
4,925,410
[ 1, 3769, 83, 1733, 3886, 565, 2989, 4232, 39, 3657, 9599, 3886, 364, 8789, 83, 1733, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8789, 83, 1733, 3886, 353, 2604, 2938, 10784, 429, 3886, 288, 203, 565, 3885, 12, 203, 3639, 1758, 4058, 67, 16, 203, 3639, 1758, 3981, 67, 16, 203, 3639, 1731, 3778, 501, 67, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 4033, 31, 203, 5666, 288, 2604, 2938, 10784, 429, 3886, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5656, 19, 26516, 19, 1429, 2938, 10784, 429, 3886, 18, 18281, 14432, 203, 565, 262, 8843, 429, 2604, 2938, 10784, 429, 3886, 12, 28339, 67, 16, 3981, 67, 16, 501, 67, 13, 2618, 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 ]
./full_match/80001/0xA5978Df9a664C56d62313EE9EAaC7930977164E4/sources/contracts/past-versions/UnlockV12.sol
* @dev Registers a new PublicLock template immplementation The template is identified by a version number Once registered, the template can be used to upgrade an existing Lock @dev This will initialize the template and revokeOwnership./ First claim the template so that no-one else could this will revert if the template was already initialized.
function addLockTemplate( address impl, uint16 version ) public onlyOwner { IPublicLock(impl).initialize( address(this), 0, address(0), 0, 0, "" ); IPublicLock(impl).renounceLockManager(); _publicLockVersions[impl] = version; _publicLockImpls[version] = impl; emit UnlockTemplateAdded(impl, version); }
5,588,039
[ 1, 10277, 279, 394, 7224, 2531, 1542, 709, 1291, 806, 367, 1021, 1542, 353, 9283, 635, 279, 1177, 1300, 12419, 4104, 16, 326, 1542, 848, 506, 1399, 358, 8400, 392, 2062, 3488, 225, 1220, 903, 4046, 326, 1542, 471, 18007, 5460, 12565, 18, 19, 5783, 7516, 326, 1542, 1427, 716, 1158, 17, 476, 469, 3377, 333, 903, 15226, 309, 326, 1542, 1703, 1818, 6454, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 527, 2531, 2283, 12, 203, 565, 1758, 9380, 16, 203, 565, 2254, 2313, 1177, 203, 225, 262, 1071, 1338, 5541, 288, 203, 203, 565, 2971, 447, 2531, 12, 11299, 2934, 11160, 12, 203, 1377, 1758, 12, 2211, 3631, 203, 1377, 374, 16, 203, 1377, 1758, 12, 20, 3631, 203, 1377, 374, 16, 203, 1377, 374, 16, 203, 1377, 1408, 203, 565, 11272, 203, 565, 2971, 447, 2531, 12, 11299, 2934, 1187, 8386, 2531, 1318, 5621, 203, 203, 565, 389, 482, 2531, 5940, 63, 11299, 65, 273, 1177, 31, 203, 565, 389, 482, 2531, 2828, 87, 63, 1589, 65, 273, 9380, 31, 203, 203, 565, 3626, 3967, 2283, 8602, 12, 11299, 16, 1177, 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 ]
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol pragma solidity ^0.5.4; interface IntVoteInterface { //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier ONLYPROPOSALOWNER208(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING modifier VOTABLE853(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING event NEWPROPOSAL588( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event EXECUTEPROPOSAL706(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VOTEPROPOSAL760( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CANCELPROPOSAL161(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING event CANCELVOTING574(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING function PROPOSE661( //inject NONSTANDARD NAMING uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns(bytes32); function VOTE536( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns(bool); function CANCELVOTE202(bytes32 _proposalId) external; //inject NONSTANDARD NAMING function GETNUMBEROFCHOICES589(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function ISVOTABLE375(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING function ISABSTAINALLOW791() external pure returns(bool); //inject NONSTANDARD NAMING function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; interface IERC20 { function TRANSFER985(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE946(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM649(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY573() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF995(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE88(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER258(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL578(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol pragma solidity ^0.5.4; interface VotingMachineCallbacksInterface { function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function BURNREPUTATION898(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function STAKINGTOKENTRANSFER53(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING external returns(bool); function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED48(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED48(address(0), _owner); } function OWNER574() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER824() { //inject NONSTANDARD NAMING require(ISOWNER625()); _; } function ISOWNER625() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP632() public ONLYOWNER824 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED48(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP334(address newOwner) public ONLYOWNER824 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP900(newOwner); } function _TRANSFEROWNERSHIP900(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED48(_owner, newOwner); _owner = newOwner; } } // File: @daostack/infra/contracts/Reputation.sol pragma solidity ^0.5.4; contract Reputation is Ownable { uint8 public decimals = 18; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event MINT335(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING // Event indicating burning of reputation for an address. event BURN261(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of reputation at a specific block number uint128 value; } // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // Tracks the history of the `totalSupply` of the reputation Checkpoint[] totalSupplyHistory; constructor( ) public { } function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING return TOTALSUPPLYAT652(block.number); } // Query balance and totalSupply in History function BALANCEOF995(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return BALANCEOFAT780(_owner, block.number); } function BALANCEOFAT780(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING public view returns (uint256) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; // This will return the expected balance during normal situations } else { return GETVALUEAT483(balances[_owner], _blockNumber); } } function TOTALSUPPLYAT652(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return GETVALUEAT483(totalSupplyHistory, _blockNumber); } } function MINT69(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY573(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = BALANCEOF995(_user); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply + _amount); UPDATEVALUEATNOW719(balances[_user], previousBalanceTo + _amount); emit MINT335(_user, _amount); return true; } function BURN206(address _user, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY573(); uint256 amountBurned = _amount; uint256 previousBalanceFrom = BALANCEOF995(_user); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } UPDATEVALUEATNOW719(totalSupplyHistory, curTotalSupply - amountBurned); UPDATEVALUEATNOW719(balances[_user], previousBalanceFrom - amountBurned); emit BURN261(_user, amountBurned); return true; } // Internal helper functions to query and set a value in a snapshot array function GETVALUEAT483(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING if (checkpoints.length == 0) { return 0; } // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function UPDATEVALUEATNOW719(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING require(uint128(_value) == _value); //check value is in the 128 bits bounderies if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; library SafeMath { function MUL295(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV1(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB141(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD15(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD36(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY573() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF995(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE88(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER985(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER402(msg.sender, to, value); return true; } function APPROVE946(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, value); return true; } function TRANSFERFROM649(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER402(from, to, value); _APPROVE913(from, msg.sender, _allowed[from][msg.sender].SUB141(value)); return true; } function INCREASEALLOWANCE616(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].ADD15(addedValue)); return true; } function DECREASEALLOWANCE72(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE913(msg.sender, spender, _allowed[msg.sender][spender].SUB141(subtractedValue)); return true; } function _TRANSFER402(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB141(value); _balances[to] = _balances[to].ADD15(value); emit TRANSFER258(from, to, value); } function _MINT318(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD15(value); _balances[account] = _balances[account].ADD15(value); emit TRANSFER258(address(0), account, value); } function _BURN875(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB141(value); _balances[account] = _balances[account].SUB141(value); emit TRANSFER258(account, address(0), value); } function _APPROVE913(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit APPROVAL578(owner, spender, value); } function _BURNFROM507(address account, uint256 value) internal { //inject NONSTANDARD NAMING _BURN875(account, value); _APPROVE913(account, msg.sender, _allowed[account][msg.sender].SUB141(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; contract ERC20Burnable is ERC20 { function BURN206(uint256 value) public { //inject NONSTANDARD NAMING _BURN875(msg.sender, value); } function BURNFROM991(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM507(from, value); } } // File: contracts/controller/DAOToken.sol pragma solidity ^0.5.4; contract DAOToken is ERC20, ERC20Burnable, Ownable { string public name; string public symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals662 = 18; //inject NONSTANDARD NAMING uint256 public cap; constructor(string memory _name, string memory _symbol, uint256 _cap) public { name = _name; symbol = _symbol; cap = _cap; } function MINT69(address _to, uint256 _amount) public ONLYOWNER824 returns (bool) { //inject NONSTANDARD NAMING if (cap > 0) require(TOTALSUPPLY573().ADD15(_amount) <= cap); _MINT318(_to, _amount); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.2; library Address { function ISCONTRACT51(address account) internal view returns (bool) { //inject NONSTANDARD NAMING uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/libs/SafeERC20.sol pragma solidity ^0.5.4; library SafeERC20 { using Address for address; bytes4 constant private transfer_selector475 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private transferfrom_selector4 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private approve_selector816 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING function SAFETRANSFER442(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transfer_selector475, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFETRANSFERFROM294(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transferfrom_selector4, _from, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFEAPPROVE771(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT51()); // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. require((_value == 0) || (IERC20(_erc20Addr).ALLOWANCE88(address(this), _spender) == 0)); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(approve_selector816, _spender, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } } // File: contracts/controller/Avatar.sol pragma solidity ^0.5.4; contract Avatar is Ownable { using SafeERC20 for address; string public orgName; DAOToken public nativeToken; Reputation public nativeReputation; event GENERICCALL988(address indexed _contract, bytes _data, uint _value, bool _success); //inject NONSTANDARD NAMING event SENDETHER194(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFER653(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFERFROM913(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENAPPROVAL142(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING event RECEIVEETHER18(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING event METADATA150(string _metaData); //inject NONSTANDARD NAMING constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } function() external payable { emit RECEIVEETHER18(msg.sender, msg.value); } function GENERICCALL327(address _contract, bytes memory _data, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool success, bytes memory returnValue) { // solhint-disable-next-line avoid-call-value (success, returnValue) = _contract.call.value(_value)(_data); emit GENERICCALL988(_contract, _data, _value, success); } function SENDETHER177(uint256 _amountInWei, address payable _to) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING _to.transfer(_amountInWei); emit SENDETHER194(_amountInWei, _to); return true; } function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool) { address(_externalToken).SAFETRANSFER442(_to, _value); emit EXTERNALTOKENTRANSFER653(address(_externalToken), _to, _value); return true; } function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING IERC20 _externalToken, address _from, address _to, uint256 _value ) public ONLYOWNER824 returns(bool) { address(_externalToken).SAFETRANSFERFROM294(_from, _to, _value); emit EXTERNALTOKENTRANSFERFROM913(address(_externalToken), _from, _to, _value); return true; } function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER824 returns(bool) { address(_externalToken).SAFEAPPROVE771(_spender, _value); emit EXTERNALTOKENAPPROVAL142(address(_externalToken), _spender, _value); return true; } function METADATA450(string memory _metaData) public ONLYOWNER824 returns(bool) { //inject NONSTANDARD NAMING emit METADATA150(_metaData); return true; } } // File: contracts/universalSchemes/UniversalSchemeInterface.sol pragma solidity ^0.5.4; contract UniversalSchemeInterface { function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING } // File: contracts/globalConstraints/GlobalConstraintInterface.sol pragma solidity ^0.5.4; contract GlobalConstraintInterface { enum CallPhase { Pre, Post, PreAndPost } function PRE222( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function POST74( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function WHEN422() public returns(CallPhase); //inject NONSTANDARD NAMING } // File: contracts/controller/ControllerInterface.sol pragma solidity ^0.5.4; interface ControllerInterface { function MINTREPUTATION981(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function BURNREPUTATION898(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function MINTTOKENS758(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REGISTERSCHEME37(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSCHEME785(address _scheme, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSELF96(address _avatar) external returns(bool); //inject NONSTANDARD NAMING function ADDGLOBALCONSTRAINT638(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REMOVEGLOBALCONSTRAINT28 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UPGRADECONTROLLER721(address _newController, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function GENERICCALL327(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value) //inject NONSTANDARD NAMING external returns(bool, bytes memory); function SENDETHER177(uint256 _amountInWei, address payable _to, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFER167(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFERFROM421( //inject NONSTANDARD NAMING IERC20 _externalToken, address _from, address _to, uint256 _value, Avatar _avatar) external returns(bool); function EXTERNALTOKENAPPROVAL190(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar) //inject NONSTANDARD NAMING external returns(bool); function METADATA450(string calldata _metaData, Avatar _avatar) external returns(bool); //inject NONSTANDARD NAMING function GETNATIVEREPUTATION762(address _avatar) //inject NONSTANDARD NAMING external view returns(address); function ISSCHEMEREGISTERED658( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING function GETSCHEMEPARAMETERS578(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETGLOBALCONSTRAINTPARAMETERS702(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETSCHEMEPERMISSIONS800(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING function GLOBALCONSTRAINTSCOUNT83(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING function ISGLOBALCONSTRAINTREGISTERED605(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING } // File: contracts/universalSchemes/UniversalScheme.sol pragma solidity ^0.5.4; contract UniversalScheme is UniversalSchemeInterface { function GETPARAMETERSFROMCONTROLLER560(Avatar _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING require(ControllerInterface(_avatar.OWNER574()).ISSCHEMEREGISTERED658(address(this), address(_avatar)), "scheme is not registered"); return ControllerInterface(_avatar.OWNER574()).GETSCHEMEPARAMETERS578(address(this), address(_avatar)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.2; library ECDSA { function RECOVER336(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } function TOETHSIGNEDMESSAGEHASH747(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: @daostack/infra/contracts/libs/RealMath.sol pragma solidity ^0.5.4; library RealMath { uint256 constant private real_bits978 = 256; //inject NONSTANDARD NAMING uint256 constant private real_fbits102 = 40; //inject NONSTANDARD NAMING uint256 constant private real_one722 = uint256(1) << real_fbits102; //inject NONSTANDARD NAMING function POW948(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 tempRealBase = realBase; uint256 tempExponent = exponent; // Start with the 0th power uint256 realResult = real_one722; while (tempExponent != 0) { // While there are still bits set if ((tempExponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base realResult = MUL295(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; if (tempExponent != 0) { // Do the squaring tempRealBase = MUL295(tempRealBase, tempRealBase); } } // Return the final result. return realResult; } function FRACTION401(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV1(uint256(numerator) * real_one722, uint256(denominator) * real_one722); } function MUL295(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. uint256 res = realA * realB; require(res/realA == realB, "RealMath mul overflow"); return (res >> real_fbits102); } function DIV1(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return uint256((uint256(realNumerator) * real_one722) / uint256(realDenominator)); } } // File: @daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol pragma solidity ^0.5.4; interface ProposalExecuteInterface { function EXECUTEPROPOSAL422(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; library Math { function MAX135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN317(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE86(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol pragma solidity ^0.5.4; contract GenesisProtocolLogic is IntVoteInterface { using SafeMath for uint256; using Math for uint256; using RealMath for uint216; using RealMath for uint256; using Address for address; enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod} enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed} //Organization's parameters struct Parameters { uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar. uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode. uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode. uint256 preBoostedVotePeriodLimit; //the time limit for a proposal //to be in an preparation state (stable) before boosted. uint256 thresholdConst; //constant for threshold calculation . //threshold =thresholdConst ** (numberOfBoostedProposals) uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals //in the threshold calculation to prevent overflow uint256 quietEndingPeriod; //quite ending period uint256 proposingRepReward;//proposer reputation reward. uint256 votersReputationLossRatio;//Unsuccessful pre booster //voters lose votersReputationLossRatio% of their reputation. uint256 minimumDaoBounty; uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula //(daoBountyConst * averageBoostDownstakes)/100 . uint256 activationTime;//the point in time after which proposals can be created. //if this address is set so only this address is allowed to vote of behalf of someone else. address voteOnBehalf; } struct Voter { uint256 vote; // YES(1) ,NO(2) uint256 reputation; // amount of voter's reputation bool preBoosted; } struct Staker { uint256 vote; // YES(1) ,NO(2) uint256 amount; // amount of staker's stake uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation. } struct Proposal { bytes32 organizationId; // the organization unique identifier the proposal is target to. address callbacks; // should fulfill voting callbacks interface. ProposalState state; uint256 winningVote; //the winning vote. address proposer; //the proposal boosted period limit . it is updated for the case of quiteWindow mode. uint256 currentBoostedVotePeriodLimit; bytes32 paramsHash; uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time. uint256 daoBounty; uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers. uint256 confidenceThreshold; //The percentage from upper stakes which the caller for the expiration was given. uint256 expirationCallBountyPercentage; uint[3] times; //times[0] - submittedTime //times[1] - boostedPhaseTime //times[2] -preBoostedPhaseTime; bool daoRedeemItsWinnings; // vote reputation mapping(uint256 => uint256 ) votes; // vote reputation mapping(uint256 => uint256 ) preBoostedVotes; // address voter mapping(address => Voter ) voters; // vote stakes mapping(uint256 => uint256 ) stakes; // address staker mapping(address => Staker ) stakers; } event STAKE754(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _staker, uint256 _vote, uint256 _amount ); event REDEEM636(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMDAOBOUNTY578(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMREPUTATION314(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event STATECHANGE374(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING event GPEXECUTEPROPOSAL538(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING event EXPIRATIONCALLBOUNTY93(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING event CONFIDENCELEVELCHANGE532(bytes32 indexed _proposalId, uint256 _confidenceThreshold); //inject NONSTANDARD NAMING mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. mapping(bytes32=>uint) public orgBoostedProposalsCnt; //organizationId => organization mapping(bytes32 => address ) public organizations; //organizationId => averageBoostDownstakes mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted; uint256 constant public num_of_choices613 = 2; //inject NONSTANDARD NAMING uint256 constant public no391 = 2; //inject NONSTANDARD NAMING uint256 constant public yes596 = 1; //inject NONSTANDARD NAMING uint256 public proposalsCnt; // Total number of proposals IERC20 public stakingToken; address constant private gen_token_address929 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING uint256 constant private max_boosted_proposals645 = 4096; //inject NONSTANDARD NAMING constructor(IERC20 _stakingToken) public { //The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS . //This will work for a network which already hosted the GEN token on this address (e.g mainnet). //If such contract address does not exist in the network (e.g ganache) //the contract will use the _stakingToken param as the //staking token address. if (address(gen_token_address929).ISCONTRACT51()) { stakingToken = IERC20(gen_token_address929); } else { stakingToken = _stakingToken; } } modifier VOTABLE853(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(_ISVOTABLE722(_proposalId)); _; } function PROPOSE661(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING external returns(bytes32) { // solhint-disable-next-line not-rely-on-time require(now > parameters[_paramsHash].activationTime, "not active yet"); //Check parameters existence. require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt = proposalsCnt.ADD15(1); // Open proposal: Proposal memory proposal; proposal.callbacks = msg.sender; proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization)); proposal.state = ProposalState.Queued; // solhint-disable-next-line not-rely-on-time proposal.times[0] = now;//submitted time proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit; proposal.proposer = _proposer; proposal.winningVote = no391; proposal.paramsHash = _paramsHash; if (organizations[proposal.organizationId] == address(0)) { if (_organization == address(0)) { organizations[proposal.organizationId] = msg.sender; } else { organizations[proposal.organizationId] = _organization; } } //calc dao bounty uint256 daoBounty = parameters[_paramsHash].daoBountyConst.MUL295(averagesDownstakesOfBoosted[proposal.organizationId]).DIV1(100); if (daoBounty < parameters[_paramsHash].minimumDaoBounty) { proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty; } else { proposal.daoBountyRemain = daoBounty; } proposal.totalStakes = proposal.daoBountyRemain; proposals[proposalId] = proposal; proposals[proposalId].stakes[no391] = proposal.daoBountyRemain;//dao downstake on the proposal emit NEWPROPOSAL588(proposalId, organizations[proposal.organizationId], num_of_choices613, _proposer, _paramsHash); return proposalId; } function EXECUTEBOOSTED17(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod, "proposal state in not Boosted nor QuietEndingPeriod"); require(_EXECUTE501(_proposalId), "proposal need to expire"); uint256 expirationCallBountyPercentage = // solhint-disable-next-line not-rely-on-time (uint(1).ADD15(now.SUB141(proposal.currentBoostedVotePeriodLimit.ADD15(proposal.times[1])).DIV1(15))); if (expirationCallBountyPercentage > 100) { expirationCallBountyPercentage = 100; } proposal.expirationCallBountyPercentage = expirationCallBountyPercentage; expirationCallBounty = expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100); require(stakingToken.TRANSFER985(msg.sender, expirationCallBounty), "transfer to msg.sender failed"); emit EXPIRATIONCALLBOUNTY93(_proposalId, msg.sender, expirationCallBounty); } function SETPARAMETERS600( //inject NONSTANDARD NAMING uint[11] calldata _params, //use array here due to stack too deep issue. address _voteOnBehalf ) external returns(bytes32) { require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100"); require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000"); require(_params[7] <= 100, "votersReputationLossRatio <= 100"); require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod"); require(_params[8] > 0, "minimumDaoBounty should be > 0"); require(_params[9] > 0, "daoBountyConst should be > 0"); bytes32 paramsHash = GETPARAMETERSHASH529(_params, _voteOnBehalf); //set a limit for power for a given alpha to prevent overflow uint256 limitExponent = 172;//for alpha less or equal 2 uint256 j = 2; for (uint256 i = 2000; i < 16000; i = i*2) { if ((_params[4] > i) && (_params[4] <= i*2)) { limitExponent = limitExponent/j; break; } j++; } parameters[paramsHash] = Parameters({ queuedVoteRequiredPercentage: _params[0], queuedVotePeriodLimit: _params[1], boostedVotePeriodLimit: _params[2], preBoostedVotePeriodLimit: _params[3], thresholdConst:uint216(_params[4]).FRACTION401(uint216(1000)), limitExponentValue:limitExponent, quietEndingPeriod: _params[5], proposingRepReward: _params[6], votersReputationLossRatio:_params[7], minimumDaoBounty:_params[8], daoBountyConst:_params[9], activationTime:_params[10], voteOnBehalf:_voteOnBehalf }); return paramsHash; } // solhint-disable-next-line function-max-lines,code-complexity function REDEEM641(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue), "Proposal should be Executed or ExpiredInQueue"); Parameters memory params = parameters[proposal.paramsHash]; uint256 lostReputation; if (proposal.winningVote == yes596) { lostReputation = proposal.preBoostedVotes[no391]; } else { lostReputation = proposal.preBoostedVotes[yes596]; } lostReputation = (lostReputation.MUL295(params.votersReputationLossRatio))/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; uint256 totalStakes = proposal.stakes[no391].ADD15(proposal.stakes[yes596]); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; if (staker.amount > 0) { uint256 totalStakesLeftAfterCallBounty = totalStakes.SUB141(proposal.expirationCallBountyPercentage.MUL295(proposal.stakes[yes596]).DIV1(100)); if (proposal.state == ProposalState.ExpiredInQueue) { //Stakes of a proposal that expires in Queue are sent back to stakers rewards[0] = staker.amount; } else if (staker.vote == proposal.winningVote) { if (staker.vote == yes596) { if (proposal.daoBounty < totalStakesLeftAfterCallBounty) { uint256 _totalStakes = totalStakesLeftAfterCallBounty.SUB141(proposal.daoBounty); rewards[0] = (staker.amount.MUL295(_totalStakes))/totalWinningStakes; } } else { rewards[0] = (staker.amount.MUL295(totalStakesLeftAfterCallBounty))/totalWinningStakes; } } staker.amount = 0; } //dao redeem its winnings if (proposal.daoRedeemItsWinnings == false && _beneficiary == organizations[proposal.organizationId] && proposal.state != ProposalState.ExpiredInQueue && proposal.winningVote == no391) { rewards[0] = rewards[0].ADD15((proposal.daoBounty.MUL295(totalStakes))/totalWinningStakes).SUB141(proposal.daoBounty); proposal.daoRedeemItsWinnings = true; } //as voter Voter storage voter = proposal.voters[_beneficiary]; if ((voter.reputation != 0) && (voter.preBoosted)) { if (proposal.state == ProposalState.ExpiredInQueue) { //give back reputation for the voter rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100); } else if (proposal.winningVote == voter.vote) { rewards[1] = ((voter.reputation.MUL295(params.votersReputationLossRatio))/100) .ADD15((voter.reputation.MUL295(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes596)&&(proposal.proposer != address(0))) { rewards[2] = params.proposingRepReward; proposal.proposer = address(0); } if (rewards[0] != 0) { proposal.totalStakes = proposal.totalStakes.SUB141(rewards[0]); require(stakingToken.TRANSFER985(_beneficiary, rewards[0]), "transfer to beneficiary failed"); emit REDEEM636(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]); } if (rewards[1].ADD15(rewards[2]) != 0) { VotingMachineCallbacksInterface(proposal.callbacks) .MINTREPUTATION981(rewards[1].ADD15(rewards[2]), _beneficiary, _proposalId); emit REDEEMREPUTATION314( _proposalId, organizations[proposal.organizationId], _beneficiary, rewards[1].ADD15(rewards[2]) ); } } function REDEEMDAOBOUNTY8(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING public returns(uint256 redeemedAmount, uint256 potentialAmount) { Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Executed); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; Staker storage staker = proposal.stakers[_beneficiary]; if ( (staker.amount4Bounty > 0)&& (staker.vote == proposal.winningVote)&& (proposal.winningVote == yes596)&& (totalWinningStakes != 0)) { //as staker potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes; } if ((potentialAmount != 0)&& (VotingMachineCallbacksInterface(proposal.callbacks) .BALANCEOFSTAKINGTOKEN878(stakingToken, _proposalId) >= potentialAmount)) { staker.amount4Bounty = 0; proposal.daoBountyRemain = proposal.daoBountyRemain.SUB141(potentialAmount); require( VotingMachineCallbacksInterface(proposal.callbacks) .STAKINGTOKENTRANSFER53(stakingToken, _beneficiary, potentialAmount, _proposalId)); redeemedAmount = potentialAmount; emit REDEEMDAOBOUNTY578(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount); } } function SHOULDBOOST603(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING Proposal memory proposal = proposals[_proposalId]; return (_SCORE635(_proposalId) > THRESHOLD53(proposal.paramsHash, proposal.organizationId)); } function THRESHOLD53(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING uint256 power = orgBoostedProposalsCnt[_organizationId]; Parameters storage params = parameters[_paramsHash]; if (power > params.limitExponentValue) { power = params.limitExponentValue; } return params.thresholdConst.POW948(power); } function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING uint[11] memory _params,//use array here due to stack too deep issue. address _voteOnBehalf ) public pure returns(bytes32) { //double call to keccak256 to avoid deep stack issue when call with too many params. return keccak256( abi.encodePacked( keccak256( abi.encodePacked( _params[0], _params[1], _params[2], _params[3], _params[4], _params[5], _params[6], _params[7], _params[8], _params[9], _params[10]) ), _voteOnBehalf )); } // solhint-disable-next-line function-max-lines,code-complexity function _EXECUTE501(bytes32 _proposalId) internal VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint256 totalReputation = VotingMachineCallbacksInterface(proposal.callbacks).GETTOTALREPUTATIONSUPPLY50(_proposalId); //first divide by 100 to prevent overflow uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage; ExecutionState executionState = ExecutionState.None; uint256 averageDownstakesOfBoosted; uint256 confidenceThreshold; if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. if (proposal.state == ProposalState.Queued) { executionState = ExecutionState.QueueBarCrossed; } else if (proposal.state == ProposalState.PreBoosted) { executionState = ExecutionState.PreBoostedBarCrossed; } else { executionState = ExecutionState.BoostedBarCrossed; } proposal.state = ProposalState.Executed; } else { if (proposal.state == ProposalState.Queued) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) { proposal.state = ProposalState.ExpiredInQueue; proposal.winningVote = no391; executionState = ExecutionState.QueueTimeOut; } else { confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId); if (_SCORE635(_proposalId) > confidenceThreshold) { //change proposal mode to PreBoosted mode. proposal.state = ProposalState.PreBoosted; // solhint-disable-next-line not-rely-on-time proposal.times[2] = now; proposal.confidenceThreshold = confidenceThreshold; } } } if (proposal.state == ProposalState.PreBoosted) { confidenceThreshold = THRESHOLD53(proposal.paramsHash, proposal.organizationId); // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) { if ((_SCORE635(_proposalId) > confidenceThreshold) && (orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals645)) { //change proposal mode to Boosted mode. proposal.state = ProposalState.Boosted; // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; orgBoostedProposalsCnt[proposal.organizationId]++; //add a value to average -> average = average + ((value - average) / nbValues) averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; // solium-disable-next-line indentation averagesDownstakesOfBoosted[proposal.organizationId] = uint256(int256(averageDownstakesOfBoosted) + ((int256(proposal.stakes[no391])-int256(averageDownstakesOfBoosted))/ int256(orgBoostedProposalsCnt[proposal.organizationId]))); } } else { //check the Confidence level is stable uint256 proposalScore = _SCORE635(_proposalId); if (proposalScore <= proposal.confidenceThreshold.MIN317(confidenceThreshold)) { proposal.state = ProposalState.Queued; } else if (proposal.confidenceThreshold > proposalScore) { proposal.confidenceThreshold = confidenceThreshold; emit CONFIDENCELEVELCHANGE532(_proposalId, confidenceThreshold); } } } } if ((proposal.state == ProposalState.Boosted) || (proposal.state == ProposalState.QuietEndingPeriod)) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) { proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedTimeOut; } } if (executionState != ExecutionState.None) { if ((executionState == ExecutionState.BoostedTimeOut) || (executionState == ExecutionState.BoostedBarCrossed)) { orgBoostedProposalsCnt[tmpProposal.organizationId] = orgBoostedProposalsCnt[tmpProposal.organizationId].SUB141(1); //remove a value from average = ((average * nbValues) - value) / (nbValues - 1); uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId]; if (boostedProposals == 0) { averagesDownstakesOfBoosted[proposal.organizationId] = 0; } else { averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; averagesDownstakesOfBoosted[proposal.organizationId] = (averageDownstakesOfBoosted.MUL295(boostedProposals+1).SUB141(proposal.stakes[no391]))/boostedProposals; } } emit EXECUTEPROPOSAL706( _proposalId, organizations[proposal.organizationId], proposal.winningVote, totalReputation ); emit GPEXECUTEPROPOSAL538(_proposalId, executionState); ProposalExecuteInterface(proposal.callbacks).EXECUTEPROPOSAL422(_proposalId, int(proposal.winningVote)); proposal.daoBounty = proposal.daoBountyRemain; } if (tmpProposal.state != proposal.state) { emit STATECHANGE374(_proposalId, proposal.state); } return (executionState != ExecutionState.None); } function _STAKE234(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING // 0 is not a valid vote. require(_vote <= num_of_choices613 && _vote > 0, "wrong vote value"); require(_amount > 0, "staking amount should be >0"); if (_EXECUTE501(_proposalId)) { return true; } Proposal storage proposal = proposals[_proposalId]; if ((proposal.state != ProposalState.PreBoosted) && (proposal.state != ProposalState.Queued)) { return false; } // enable to increase stake only on the previous stake vote Staker storage staker = proposal.stakers[_staker]; if ((staker.amount > 0) && (staker.vote != _vote)) { return false; } uint256 amount = _amount; require(stakingToken.TRANSFERFROM649(_staker, address(this), amount), "fail transfer from staker"); proposal.totalStakes = proposal.totalStakes.ADD15(amount); //update totalRedeemableStakes staker.amount = staker.amount.ADD15(amount); //This is to prevent average downstakes calculation overflow //Note that any how GEN cap is 100000000 ether. require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high"); require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high"); if (_vote == yes596) { staker.amount4Bounty = staker.amount4Bounty.ADD15(amount); } staker.vote = _vote; proposal.stakes[_vote] = amount.ADD15(proposal.stakes[_vote]); emit STAKE754(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount); return _EXECUTE501(_proposalId); } // solhint-disable-next-line function-max-lines,code-complexity function INTERNALVOTE757(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING require(_vote <= num_of_choices613 && _vote > 0, "0 < _vote <= 2"); if (_EXECUTE501(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).REPUTATIONOF984(_voter, _proposalId); require(reputation > 0, "_voter must have reputation"); require(reputation >= _rep, "reputation >= _rep"); uint256 rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, return false. if (proposal.voters[_voter].reputation != 0) { return false; } // The voting itself: proposal.votes[_vote] = rep.ADD15(proposal.votes[_vote]); //check if the current winningVote changed or there is a tie. //for the case there is a tie the current winningVote set to NO. if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) || ((proposal.votes[no391] == proposal.votes[proposal.winningVote]) && proposal.winningVote == yes596)) { if (proposal.state == ProposalState.Boosted && // solhint-disable-next-line not-rely-on-time ((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))|| proposal.state == ProposalState.QuietEndingPeriod) { //quietEndingPeriod if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) }); if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) { proposal.preBoostedVotes[_vote] = rep.ADD15(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.MUL295(rep))/100; VotingMachineCallbacksInterface(proposal.callbacks).BURNREPUTATION898(reputationDeposit, _voter, _proposalId); } emit VOTEPROPOSAL760(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _EXECUTE501(_proposalId); } function _SCORE635(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; //proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal. return uint216(proposal.stakes[yes596]).FRACTION401(uint216(proposal.stakes[no391])); } function _ISVOTABLE722(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol pragma solidity ^0.5.4; contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic { using ECDSA for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant delegation_hash_eip712291 = //inject NONSTANDARD NAMING keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce constructor(IERC20 _stakingToken) public // solhint-disable-next-line no-empty-blocks GenesisProtocolLogic(_stakingToken) { } function STAKE53(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING return _STAKE234(_proposalId, _vote, _amount, msg.sender); } function STAKEWITHSIGNATURE42( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( delegation_hash_eip712291, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).TOETHSIGNEDMESSAGEHASH747(); } address staker = delegationDigest.RECOVER336(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].ADD15(1); return _STAKE234(_proposalId, _vote, _amount, staker); } function VOTE536(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING external VOTABLE853(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return INTERNALVOTE757(_proposalId, voter, _vote, _amount); } function CANCELVOTE202(bytes32 _proposalId) external VOTABLE853(_proposalId) { //inject NONSTANDARD NAMING //this is not allowed return; } function EXECUTE916(bytes32 _proposalId) external VOTABLE853(_proposalId) returns(bool) { //inject NONSTANDARD NAMING return _EXECUTE501(_proposalId); } function GETNUMBEROFCHOICES589(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING return num_of_choices613; } function GETPROPOSALTIMES314(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING return proposals[_proposalId].times; } function VOTEINFO167(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } function VOTESTATUS96(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].votes[_choice]; } function ISVOTABLE375(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING return _ISVOTABLE722(_proposalId); } function PROPOSALSTATUS186(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING return ( proposals[_proposalId].preBoostedVotes[yes596], proposals[_proposalId].preBoostedVotes[no391], proposals[_proposalId].stakes[yes596], proposals[_proposalId].stakes[no391] ); } function GETPROPOSALORGANIZATION49(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING return (proposals[_proposalId].organizationId); } function GETSTAKER814(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } function VOTESTAKE56(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].stakes[_vote]; } function WINNINGVOTE889(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].winningVote; } function STATE293(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING return proposals[_proposalId].state; } function ISABSTAINALLOW791() external pure returns(bool) { //inject NONSTANDARD NAMING return false; } function GETALLOWEDRANGEOFCHOICES990() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING return (yes596, no391); } function SCORE81(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING return _SCORE635(_proposalId); } } // File: contracts/votingMachines/VotingMachineCallbacks.sol pragma solidity ^0.5.4; contract VotingMachineCallbacks is VotingMachineCallbacksInterface { struct ProposalInfo { uint256 blockNumber; // the proposal's block number Avatar avatar; // the proposal's avatar } modifier ONLYVOTINGMACHINE284(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine"); _; } // VotingMaching -> proposalId -> ProposalInfo mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo; function MINTREPUTATION981(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).MINTREPUTATION981(_amount, _beneficiary, address(avatar)); } function BURNREPUTATION898(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).BURNREPUTATION898(_amount, _beneficiary, address(avatar)); } function STAKINGTOKENTRANSFER53( //inject NONSTANDARD NAMING IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.OWNER574()).EXTERNALTOKENTRANSFER167(_stakingToken, _beneficiary, _amount, avatar); } function BALANCEOFSTAKINGTOKEN878(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) { return 0; } return _stakingToken.BALANCEOF995(address(avatar)); } function GETTOTALREPUTATIONSUPPLY50(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().TOTALSUPPLYAT652(proposal.blockNumber); } function REPUTATIONOF984(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().BALANCEOFAT780(_owner, proposal.blockNumber); } } // File: contracts/universalSchemes/SchemeRegistrar.sol pragma solidity ^0.5.4; contract SchemeRegistrar is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface { event NEWSCHEMEPROPOSAL971( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string _descriptionHash ); event REMOVESCHEMEPROPOSAL965(address indexed _avatar, //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, string _descriptionHash ); event PROPOSALEXECUTED934(address indexed _avatar, bytes32 indexed _proposalId, int256 _param); //inject NONSTANDARD NAMING event PROPOSALDELETED307(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING // a SchemeProposal is a proposal to add or remove a scheme to/from the an organization struct SchemeProposal { address scheme; // bool addScheme; // true: add a scheme, false: remove a scheme. bytes32 parametersHash; bytes4 permissions; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address=>mapping(bytes32=>SchemeProposal)) public organizationsProposals; // A mapping from hashes to parameters (use to store a particular configuration on the controller) struct Parameters { bytes32 voteRegisterParams; bytes32 voteRemoveParams; IntVoteInterface intVote; } mapping(bytes32=>Parameters) public parameters; function EXECUTEPROPOSAL422(bytes32 _proposalId, int256 _param) external ONLYVOTINGMACHINE284(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; SchemeProposal memory proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.scheme != address(0)); delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED307(address(avatar), _proposalId); if (_param == 1) { // Define controller and get the params: ControllerInterface controller = ControllerInterface(avatar.OWNER574()); // Add a scheme: if (proposal.addScheme) { require(controller.REGISTERSCHEME37( proposal.scheme, proposal.parametersHash, proposal.permissions, address(avatar)) ); } // Remove a scheme: if (!proposal.addScheme) { require(controller.UNREGISTERSCHEME785(proposal.scheme, address(avatar))); } } emit PROPOSALEXECUTED934(address(avatar), _proposalId, _param); return true; } function SETPARAMETERS600( //inject NONSTANDARD NAMING bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public returns(bytes32) { bytes32 paramsHash = GETPARAMETERSHASH529(_voteRegisterParams, _voteRemoveParams, _intVote); parameters[paramsHash].voteRegisterParams = _voteRegisterParams; parameters[paramsHash].voteRemoveParams = _voteRemoveParams; parameters[paramsHash].intVote = _intVote; return paramsHash; } function GETPARAMETERSHASH529( //inject NONSTANDARD NAMING bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_voteRegisterParams, _voteRemoveParams, _intVote)); } function PROPOSESCHEME503( //inject NONSTANDARD NAMING Avatar _avatar, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string memory _descriptionHash ) public returns(bytes32) { // propose require(_scheme != address(0), "scheme cannot be zero"); Parameters memory controllerParams = parameters[GETPARAMETERSFROMCONTROLLER560(_avatar)]; bytes32 proposalId = controllerParams.intVote.PROPOSE661( 2, controllerParams.voteRegisterParams, msg.sender, address(_avatar) ); SchemeProposal memory proposal = SchemeProposal({ scheme: _scheme, parametersHash: _parametersHash, addScheme: true, permissions: _permissions }); emit NEWSCHEMEPROPOSAL971( address(_avatar), proposalId, address(controllerParams.intVote), _scheme, _parametersHash, _permissions, _descriptionHash ); organizationsProposals[address(_avatar)][proposalId] = proposal; proposalsInfo[address(controllerParams.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } function PROPOSETOREMOVESCHEME279(Avatar _avatar, address _scheme, string memory _descriptionHash) //inject NONSTANDARD NAMING public returns(bytes32) { require(_scheme != address(0), "scheme cannot be zero"); bytes32 paramsHash = GETPARAMETERSFROMCONTROLLER560(_avatar); Parameters memory params = parameters[paramsHash]; IntVoteInterface intVote = params.intVote; bytes32 proposalId = intVote.PROPOSE661(2, params.voteRemoveParams, msg.sender, address(_avatar)); organizationsProposals[address(_avatar)][proposalId].scheme = _scheme; emit REMOVESCHEMEPROPOSAL965(address(_avatar), proposalId, address(intVote), _scheme, _descriptionHash); proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } }
inject NONSTANDARD NAMING
function _BURN875(address account, uint256 value) internal {
15,855,658
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 38, 8521, 28, 5877, 12, 2867, 2236, 16, 2254, 5034, 460, 13, 2713, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; import "./Auction.sol"; contract VickreyAuction is Auction { uint public minimumPrice; uint public biddingDeadline; uint public revealDeadline; uint public bidDepositAmount; // TODO: place your code here uint oldBalance; uint highestBidThusFar; uint bidValue; address highestBidderThusFar; bytes32 bid_bytes; uint secondHighestBid; bytes32 supposedHash; mapping(address=>bytes32) memory commitments; mapping(address=>uint) memory bids; event print(bytes32 b3 ); event printInt(uint u); event printStr(string str); event printAdd(address add); // constructor constructor(address _sellerAddress, address _judgeAddress, address _timerAddress, uint _minimumPrice, uint _biddingPeriod, uint _revealPeriod, uint _bidDepositAmount) public Auction (_sellerAddress, _judgeAddress, _timerAddress) { minimumPrice = _minimumPrice; bidDepositAmount = _bidDepositAmount; secondHighestBid = minimumPrice; biddingDeadline = time() + _biddingPeriod; revealDeadline = time() + _biddingPeriod + _revealPeriod; // TODO: place your code here } modifier onlyInTimePeriod(uint endTime) { require( endTime > time(), "Out of auction time window."); _; } modifier onlyAfter(uint startTime) { require( time() >= startTime, "Cannot be called yet."); _; } // Record the player's bid commitment // Make sure exactly bidDepositAmount is provided (for new bids) // Bidders can update their previous bid for free if desired. // Only allow commitments before biddingDeadline function commitBid(bytes32 bidCommitment) public payable onlyInTimePeriod(biddingDeadline) { // // NOOP to silence compiler warning. Delete me. // bidCommitment ^= 0; bytes32 commitment = commitments[msg.sender]; // TODO: place your code here if (commitment==0) // If it is not zero, then we can update the commitment for free. if (address(this).balance != oldBalance + bidDepositAmount) revert('Deposit is not correct'); if (commitment!=0 && address(this).balance != oldBalance) revert('No need for another deposit.'); commitments[msg.sender] = bidCommitment; oldBalance = address(this).balance; } function checkHashes(bytes32 nonce) internal returns (bool matches){ bidValue = address(this).balance - oldBalance; bid_bytes = bytes32(bidValue); supposedHash = keccak256(abi.encodePacked(bid_bytes, nonce)); if (supposedHash != commitments[msg.sender]) { return false; } return true; } // Check that the bid (msg.value) matches the commitment. // If the bid is correctly opened, the bidder can withdraw their deposit. function revealBid(bytes32 nonce) public payable onlyAfter(biddingDeadline) onlyInTimePeriod(revealDeadline) returns(bool isHighestBidder) { // // NOOPs to silence compiler warning. Delete me. // nonce ^= 0; isHighestBidder = false; // TODO: place your code here // emit printStr("Supposed"); // emit print(supposedHash); // emit printStr("should be in hashmap: "); // emit print(commitments[msg.sender]); if (!checkHashes(nonce)) revert("Something does not hash out..."); delete commitments[msg.sender]; bidValue = address(this).balance - oldBalance; bids[msg.sender] = bidValue; if (bidValue > highestBidThusFar) { if (bidValue >= minimumPrice) isHighestBidder = true; if (highestBidThusFar != 0) secondHighestBid = highestBidThusFar; highestBidThusFar = bidValue; highestBidderThusFar = msg.sender; // emit printStr("Updating highest bidder"); // emit printAdd(msg.sender); } else { secondHighestBid = bidValue; } oldBalance = address(this).balance; return isHighestBidder; } // Need to override the default implementation function getWinner() public view onlyAfter(revealDeadline) returns (address winner) { // TODO: place your code here // emit printStr("highest bidder is"); // emit printAdd(highestBidderThusFar); winner = highestBidderThusFar; return winner; } // finalize() must be extended here to provide a refund to the winner // based on the final sale price (the second highest bid, or reserve price). function finalize() public onlyAfter(revealDeadline) { // TODO: place your code here emit printStr("highest"); emit printInt(highestBidThusFar); emit printStr("minus second"); emit printInt(secondHighestBid); bids[highestBidderThusFar] = highestBidThusFar - secondHighestBid; } function withdraw() public { emit printStr("withdraw"); emit printInt(bidDepositAmount); emit printInt(address(this).balance); if (bids[msg.sender]!=0) { msg.sender.transfer(bidDepositAmount + bids[msg.sender]); } else { msg.sender.transfer(bidDepositAmount); } delete bids[msg.sender]; } }
Record the player's bid commitment Make sure exactly bidDepositAmount is provided (for new bids) Bidders can update their previous bid for free if desired. Only allow commitments before biddingDeadline NOOP to silence compiler warning. Delete me. bidCommitment ^= 0; TODO: place your code here
function commitBid(bytes32 bidCommitment) public payable onlyInTimePeriod(biddingDeadline) { bytes32 commitment = commitments[msg.sender]; if (address(this).balance != oldBalance + bidDepositAmount) revert('Deposit is not correct'); if (commitment!=0 && address(this).balance != oldBalance) revert('No need for another deposit.'); commitments[msg.sender] = bidCommitment; oldBalance = address(this).balance; }
1,049,405
[ 1, 2115, 326, 7291, 1807, 9949, 23274, 4344, 3071, 8950, 9949, 758, 1724, 6275, 353, 2112, 261, 1884, 394, 30534, 13, 605, 1873, 414, 848, 1089, 3675, 2416, 9949, 364, 4843, 309, 6049, 18, 5098, 1699, 3294, 1346, 1865, 324, 1873, 310, 15839, 225, 3741, 3665, 358, 31468, 5274, 3436, 18, 2504, 1791, 18, 9949, 5580, 475, 10352, 374, 31, 2660, 30, 3166, 3433, 981, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3294, 17763, 12, 3890, 1578, 9949, 5580, 475, 13, 1071, 8843, 429, 1338, 382, 26540, 12, 70, 1873, 310, 15839, 13, 288, 203, 9506, 202, 3890, 1578, 23274, 273, 3294, 1346, 63, 3576, 18, 15330, 15533, 203, 1850, 309, 261, 2867, 12, 2211, 2934, 12296, 480, 1592, 13937, 397, 9949, 758, 1724, 6275, 13, 15226, 2668, 758, 1724, 353, 486, 3434, 8284, 203, 3639, 309, 261, 7371, 475, 5, 33, 20, 597, 1758, 12, 2211, 2934, 12296, 480, 1592, 13937, 13, 15226, 2668, 2279, 1608, 364, 4042, 443, 1724, 1093, 1769, 203, 3639, 3294, 1346, 63, 3576, 18, 15330, 65, 273, 9949, 5580, 475, 31, 203, 3639, 1592, 13937, 273, 1758, 12, 2211, 2934, 12296, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-08 */ // Sources flattened with hardhat v2.4.0 https://hardhat.org // File contracts/auxiliary/interfaces/v0.8.4/IERC20Aux.sol pragma solidity 0.8.4; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Aux { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/auxiliary/interfaces/v0.8.4/IApi3Token.sol pragma solidity 0.8.4; interface IApi3Token is IERC20Aux { event MinterStatusUpdated( address indexed minterAddress, bool minterStatus ); event BurnerStatusUpdated( address indexed burnerAddress, bool burnerStatus ); function updateMinterStatus( address minterAddress, bool minterStatus ) external; function updateBurnerStatus(bool burnerStatus) external; function mint( address account, uint256 amount ) external; function burn(uint256 amount) external; function getMinterStatus(address minterAddress) external view returns (bool minterStatus); function getBurnerStatus(address burnerAddress) external view returns (bool burnerStatus); } // File contracts/interfaces/IStateUtils.sol pragma solidity 0.8.4; interface IStateUtils { event SetDaoApps( address agentAppPrimary, address agentAppSecondary, address votingAppPrimary, address votingAppSecondary ); event SetClaimsManagerStatus( address indexed claimsManager, bool indexed status ); event SetStakeTarget(uint256 stakeTarget); event SetMaxApr(uint256 maxApr); event SetMinApr(uint256 minApr); event SetUnstakeWaitPeriod(uint256 unstakeWaitPeriod); event SetAprUpdateStep(uint256 aprUpdateStep); event SetProposalVotingPowerThreshold(uint256 proposalVotingPowerThreshold); event UpdatedLastProposalTimestamp( address indexed user, uint256 lastProposalTimestamp, address votingApp ); function setDaoApps( address _agentAppPrimary, address _agentAppSecondary, address _votingAppPrimary, address _votingAppSecondary ) external; function setClaimsManagerStatus( address claimsManager, bool status ) external; function setStakeTarget(uint256 _stakeTarget) external; function setMaxApr(uint256 _maxApr) external; function setMinApr(uint256 _minApr) external; function setUnstakeWaitPeriod(uint256 _unstakeWaitPeriod) external; function setAprUpdateStep(uint256 _aprUpdateStep) external; function setProposalVotingPowerThreshold(uint256 _proposalVotingPowerThreshold) external; function updateLastProposalTimestamp(address userAddress) external; function isGenesisEpoch() external view returns (bool); } // File contracts/StateUtils.sol pragma solidity 0.8.4; /// @title Contract that keeps state variables contract StateUtils is IStateUtils { struct Checkpoint { uint32 fromBlock; uint224 value; } struct AddressCheckpoint { uint32 fromBlock; address _address; } struct Reward { uint32 atBlock; uint224 amount; uint256 totalSharesThen; uint256 totalStakeThen; } struct User { Checkpoint[] shares; Checkpoint[] delegatedTo; AddressCheckpoint[] delegates; uint256 unstaked; uint256 vesting; uint256 unstakeAmount; uint256 unstakeShares; uint256 unstakeScheduledFor; uint256 lastDelegationUpdateTimestamp; uint256 lastProposalTimestamp; } struct LockedCalculation { uint256 initialIndEpoch; uint256 nextIndEpoch; uint256 locked; } /// @notice Length of the epoch in which the staking reward is paid out /// once. It is hardcoded as 7 days. /// @dev In addition to regulating reward payments, this variable is used /// for two additional things: /// (1) After a user makes a proposal, they cannot make a second one /// before `EPOCH_LENGTH` has passed /// (2) After a user updates their delegation status, they have to wait /// `EPOCH_LENGTH` before updating it again uint256 public constant EPOCH_LENGTH = 1 weeks; /// @notice Number of epochs before the staking rewards get unlocked. /// Hardcoded as 52 epochs, which approximately corresponds to a year with /// an `EPOCH_LENGTH` of 1 week. uint256 public constant REWARD_VESTING_PERIOD = 52; // All percentage values are represented as 1e18 = 100% uint256 internal constant ONE_PERCENT = 1e18 / 100; uint256 internal constant HUNDRED_PERCENT = 1e18; // To assert that typecasts do not overflow uint256 internal constant MAX_UINT32 = 2**32 - 1; uint256 internal constant MAX_UINT224 = 2**224 - 1; /// @notice Epochs are indexed as `block.timestamp / EPOCH_LENGTH`. /// `genesisEpoch` is the index of the epoch in which the pool is deployed. /// @dev No reward gets paid and proposals are not allowed in the genesis /// epoch uint256 public immutable genesisEpoch; /// @notice API3 token contract IApi3Token public immutable api3Token; /// @notice TimelockManager contract address public immutable timelockManager; /// @notice Address of the primary Agent app of the API3 DAO /// @dev Primary Agent can be operated through the primary Api3Voting app. /// The primary Api3Voting app requires a higher quorum by default, and the /// primary Agent is more privileged. address public agentAppPrimary; /// @notice Address of the secondary Agent app of the API3 DAO /// @dev Secondary Agent can be operated through the secondary Api3Voting /// app. The secondary Api3Voting app requires a lower quorum by default, /// and the primary Agent is less privileged. address public agentAppSecondary; /// @notice Address of the primary Api3Voting app of the API3 DAO /// @dev Used to operate the primary Agent address public votingAppPrimary; /// @notice Address of the secondary Api3Voting app of the API3 DAO /// @dev Used to operate the secondary Agent address public votingAppSecondary; /// @notice Mapping that keeps the claims manager statuses of addresses /// @dev A claims manager is a contract that is authorized to pay out /// claims from the staking pool, effectively slashing the stakers. The /// statuses are kept as a mapping to support multiple claims managers. mapping(address => bool) public claimsManagerStatus; /// @notice Records of rewards paid in each epoch /// @dev `.atBlock` of a past epoch's reward record being `0` means no /// reward was paid for that epoch mapping(uint256 => Reward) public epochIndexToReward; /// @notice Epoch index of the most recent reward uint256 public epochIndexOfLastReward; /// @notice Total number of tokens staked at the pool uint256 public totalStake; /// @notice Stake target the pool will aim to meet in percentages of the /// total token supply. The staking rewards increase if the total staked /// amount is below this, and vice versa. /// @dev Default value is 50% of the total API3 token supply. This /// parameter is governable by the DAO. uint256 public stakeTarget = ONE_PERCENT * 50; /// @notice Minimum APR (annual percentage rate) the pool will pay as /// staking rewards in percentages /// @dev Default value is 2.5%. This parameter is governable by the DAO. uint256 public minApr = ONE_PERCENT * 25 / 10; /// @notice Maximum APR (annual percentage rate) the pool will pay as /// staking rewards in percentages /// @dev Default value is 75%. This parameter is governable by the DAO. uint256 public maxApr = ONE_PERCENT * 75; /// @notice Steps in which APR will be updated in percentages /// @dev Default value is 1%. This parameter is governable by the DAO. uint256 public aprUpdateStep = ONE_PERCENT; /// @notice Users need to schedule an unstake and wait for /// `unstakeWaitPeriod` before being able to unstake. This is to prevent /// the stakers from frontrunning insurance claims by unstaking to evade /// them, or repeatedly unstake/stake to work around the proposal spam /// protection. The tokens awaiting to be unstaked during this period do /// not grant voting power or rewards. /// @dev This parameter is governable by the DAO, and the DAO is expected /// to set this to a value that is large enough to allow insurance claims /// to be resolved. uint256 public unstakeWaitPeriod = EPOCH_LENGTH; /// @notice Minimum voting power the users must have to be able to make /// proposals (in percentages) /// @dev Delegations count towards voting power. /// Default value is 0.1%. This parameter is governable by the DAO. uint256 public proposalVotingPowerThreshold = ONE_PERCENT / 10; /// @notice APR that will be paid next epoch /// @dev This value will reach an equilibrium based on the stake target. /// Every epoch (week), APR/52 of the total staked tokens will be added to /// the pool, effectively distributing them to the stakers. uint256 public apr = (maxApr + minApr) / 2; /// @notice User records mapping(address => User) public users; // Keeps the total number of shares of the pool Checkpoint[] public poolShares; // Keeps user states used in `withdrawPrecalculated()` calls mapping(address => LockedCalculation) public userToLockedCalculation; // Kept to prevent third parties from frontrunning the initialization // `setDaoApps()` call and grief the deployment address private deployer; /// @dev Reverts if the caller is not an API3 DAO Agent modifier onlyAgentApp() { require( msg.sender == agentAppPrimary || msg.sender == agentAppSecondary, "Pool: Caller not agent" ); _; } /// @dev Reverts if the caller is not the primary API3 DAO Agent modifier onlyAgentAppPrimary() { require( msg.sender == agentAppPrimary, "Pool: Caller not primary agent" ); _; } /// @dev Reverts if the caller is not an API3 DAO Api3Voting app modifier onlyVotingApp() { require( msg.sender == votingAppPrimary || msg.sender == votingAppSecondary, "Pool: Caller not voting app" ); _; } /// @param api3TokenAddress API3 token contract address /// @param timelockManagerAddress Timelock manager contract address constructor( address api3TokenAddress, address timelockManagerAddress ) { require( api3TokenAddress != address(0), "Pool: Invalid Api3Token" ); require( timelockManagerAddress != address(0), "Pool: Invalid TimelockManager" ); deployer = msg.sender; api3Token = IApi3Token(api3TokenAddress); timelockManager = timelockManagerAddress; // Initialize the share price at 1 updateCheckpointArray(poolShares, 1); totalStake = 1; // Set the current epoch as the genesis epoch and skip its reward // payment uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; genesisEpoch = currentEpoch; epochIndexOfLastReward = currentEpoch; } /// @notice Called after deployment to set the addresses of the DAO apps /// @dev This can also be called later on by the primary Agent to update /// all app addresses as a means of an upgrade /// @param _agentAppPrimary Address of the primary Agent /// @param _agentAppSecondary Address of the secondary Agent /// @param _votingAppPrimary Address of the primary Api3Voting app /// @param _votingAppSecondary Address of the secondary Api3Voting app function setDaoApps( address _agentAppPrimary, address _agentAppSecondary, address _votingAppPrimary, address _votingAppSecondary ) external override { // solhint-disable-next-line reason-string require( msg.sender == agentAppPrimary || (agentAppPrimary == address(0) && msg.sender == deployer), "Pool: Caller not primary agent or deployer initializing values" ); require( _agentAppPrimary != address(0) && _agentAppSecondary != address(0) && _votingAppPrimary != address(0) && _votingAppSecondary != address(0), "Pool: Invalid DAO apps" ); agentAppPrimary = _agentAppPrimary; agentAppSecondary = _agentAppSecondary; votingAppPrimary = _votingAppPrimary; votingAppSecondary = _votingAppSecondary; emit SetDaoApps( agentAppPrimary, agentAppSecondary, votingAppPrimary, votingAppSecondary ); } /// @notice Called by the primary DAO Agent to set the authorization status /// of a claims manager contract /// @dev The claims manager is a trusted contract that is allowed to /// withdraw as many tokens as it wants from the pool to pay out insurance /// claims. /// Only the primary Agent can do this because it is a critical operation. /// WARNING: A compromised contract being given claims manager status may /// result in loss of staked funds. If a proposal has been made to call /// this method to set a contract as a claims manager, you are recommended /// to review the contract yourself and/or refer to the audit reports to /// understand the implications. /// @param claimsManager Claims manager contract address /// @param status Authorization status function setClaimsManagerStatus( address claimsManager, bool status ) external override onlyAgentAppPrimary() { claimsManagerStatus[claimsManager] = status; emit SetClaimsManagerStatus( claimsManager, status ); } /// @notice Called by the DAO Agent to set the stake target /// @param _stakeTarget Stake target function setStakeTarget(uint256 _stakeTarget) external override onlyAgentApp() { require( _stakeTarget <= HUNDRED_PERCENT, "Pool: Invalid percentage value" ); stakeTarget = _stakeTarget; emit SetStakeTarget(_stakeTarget); } /// @notice Called by the DAO Agent to set the maximum APR /// @param _maxApr Maximum APR function setMaxApr(uint256 _maxApr) external override onlyAgentApp() { require( _maxApr >= minApr, "Pool: Max APR smaller than min" ); maxApr = _maxApr; emit SetMaxApr(_maxApr); } /// @notice Called by the DAO Agent to set the minimum APR /// @param _minApr Minimum APR function setMinApr(uint256 _minApr) external override onlyAgentApp() { require( _minApr <= maxApr, "Pool: Min APR larger than max" ); minApr = _minApr; emit SetMinApr(_minApr); } /// @notice Called by the primary DAO Agent to set the unstake waiting /// period /// @dev This may want to be increased to provide more time for insurance /// claims to be resolved. /// Even when the insurance functionality is not implemented, the minimum /// valid value is `EPOCH_LENGTH` to prevent users from unstaking, /// withdrawing and staking with another address to work around the /// proposal spam protection. /// Only the primary Agent can do this because it is a critical operation. /// @param _unstakeWaitPeriod Unstake waiting period function setUnstakeWaitPeriod(uint256 _unstakeWaitPeriod) external override onlyAgentAppPrimary() { require( _unstakeWaitPeriod >= EPOCH_LENGTH, "Pool: Period shorter than epoch" ); unstakeWaitPeriod = _unstakeWaitPeriod; emit SetUnstakeWaitPeriod(_unstakeWaitPeriod); } /// @notice Called by the primary DAO Agent to set the APR update steps /// @dev aprUpdateStep can be 0% or 100%+. /// Only the primary Agent can do this because it is a critical operation. /// @param _aprUpdateStep APR update steps function setAprUpdateStep(uint256 _aprUpdateStep) external override onlyAgentAppPrimary() { aprUpdateStep = _aprUpdateStep; emit SetAprUpdateStep(_aprUpdateStep); } /// @notice Called by the primary DAO Agent to set the voting power /// threshold for proposals /// @dev Only the primary Agent can do this because it is a critical /// operation. /// @param _proposalVotingPowerThreshold Voting power threshold for /// proposals function setProposalVotingPowerThreshold(uint256 _proposalVotingPowerThreshold) external override onlyAgentAppPrimary() { require( _proposalVotingPowerThreshold >= ONE_PERCENT / 10 && _proposalVotingPowerThreshold <= ONE_PERCENT * 10, "Pool: Threshold outside limits"); proposalVotingPowerThreshold = _proposalVotingPowerThreshold; emit SetProposalVotingPowerThreshold(_proposalVotingPowerThreshold); } /// @notice Called by a DAO Api3Voting app at proposal creation-time to /// update the timestamp of the user's last proposal /// @param userAddress User address function updateLastProposalTimestamp(address userAddress) external override onlyVotingApp() { users[userAddress].lastProposalTimestamp = block.timestamp; emit UpdatedLastProposalTimestamp( userAddress, block.timestamp, msg.sender ); } /// @notice Called to check if we are in the genesis epoch /// @dev Voting apps use this to prevent proposals from being made in the /// genesis epoch /// @return If the current epoch is the genesis epoch function isGenesisEpoch() external view override returns (bool) { return block.timestamp / EPOCH_LENGTH == genesisEpoch; } /// @notice Called internally to update a checkpoint array by pushing a new /// checkpoint /// @dev We assume `block.number` will always fit in a uint32 and `value` /// will always fit in a uint224. `value` will either be a raw token amount /// or a raw pool share amount so this assumption will be correct in /// practice with a token with 18 decimals, 1e8 initial total supply and no /// hyperinflation. /// @param checkpointArray Checkpoint array /// @param value Value to be used to create the new checkpoint function updateCheckpointArray( Checkpoint[] storage checkpointArray, uint256 value ) internal { assert(block.number <= MAX_UINT32); assert(value <= MAX_UINT224); checkpointArray.push(Checkpoint({ fromBlock: uint32(block.number), value: uint224(value) })); } /// @notice Called internally to update an address-checkpoint array by /// pushing a new checkpoint /// @dev We assume `block.number` will always fit in a uint32 /// @param addressCheckpointArray Address-checkpoint array /// @param _address Address to be used to create the new checkpoint function updateAddressCheckpointArray( AddressCheckpoint[] storage addressCheckpointArray, address _address ) internal { assert(block.number <= MAX_UINT32); addressCheckpointArray.push(AddressCheckpoint({ fromBlock: uint32(block.number), _address: _address })); } } // File contracts/interfaces/IGetterUtils.sol pragma solidity 0.8.4; interface IGetterUtils is IStateUtils { function userVotingPowerAt( address userAddress, uint256 _block ) external view returns (uint256); function userVotingPower(address userAddress) external view returns (uint256); function totalSharesAt(uint256 _block) external view returns (uint256); function totalShares() external view returns (uint256); function userSharesAt( address userAddress, uint256 _block ) external view returns (uint256); function userShares(address userAddress) external view returns (uint256); function userStake(address userAddress) external view returns (uint256); function delegatedToUserAt( address userAddress, uint256 _block ) external view returns (uint256); function delegatedToUser(address userAddress) external view returns (uint256); function userDelegateAt( address userAddress, uint256 _block ) external view returns (address); function userDelegate(address userAddress) external view returns (address); function userLocked(address userAddress) external view returns (uint256); function getUser(address userAddress) external view returns ( uint256 unstaked, uint256 vesting, uint256 unstakeShares, uint256 unstakeAmount, uint256 unstakeScheduledFor, uint256 lastDelegationUpdateTimestamp, uint256 lastProposalTimestamp ); } // File contracts/GetterUtils.sol pragma solidity 0.8.4; /// @title Contract that implements getters abstract contract GetterUtils is StateUtils, IGetterUtils { /// @notice Called to get the voting power of a user at a specific block /// @param userAddress User address /// @param _block Block number for which the query is being made for /// @return Voting power of the user at the block function userVotingPowerAt( address userAddress, uint256 _block ) public view override returns (uint256) { // Users that have a delegate have no voting power if (userDelegateAt(userAddress, _block) != address(0)) { return 0; } return userSharesAt(userAddress, _block) + delegatedToUserAt(userAddress, _block); } /// @notice Called to get the current voting power of a user /// @param userAddress User address /// @return Current voting power of the user function userVotingPower(address userAddress) external view override returns (uint256) { return userVotingPowerAt(userAddress, block.number); } /// @notice Called to get the total pool shares at a specific block /// @dev Total pool shares also corresponds to total voting power /// @param _block Block number for which the query is being made for /// @return Total pool shares at the block function totalSharesAt(uint256 _block) public view override returns (uint256) { return getValueAt(poolShares, _block); } /// @notice Called to get the current total pool shares /// @dev Total pool shares also corresponds to total voting power /// @return Current total pool shares function totalShares() public view override returns (uint256) { return totalSharesAt(block.number); } /// @notice Called to get the pool shares of a user at a specific block /// @param userAddress User address /// @param _block Block number for which the query is being made for /// @return Pool shares of the user at the block function userSharesAt( address userAddress, uint256 _block ) public view override returns (uint256) { return getValueAt(users[userAddress].shares, _block); } /// @notice Called to get the current pool shares of a user /// @param userAddress User address /// @return Current pool shares of the user function userShares(address userAddress) public view override returns (uint256) { return userSharesAt(userAddress, block.number); } /// @notice Called to get the current staked tokens of the user /// @param userAddress User address /// @return Current staked tokens of the user function userStake(address userAddress) public view override returns (uint256) { return userShares(userAddress) * totalStake / totalShares(); } /// @notice Called to get the voting power delegated to a user at a /// specific block /// @param userAddress User address /// @param _block Block number for which the query is being made for /// @return Voting power delegated to the user at the block function delegatedToUserAt( address userAddress, uint256 _block ) public view override returns (uint256) { return getValueAt(users[userAddress].delegatedTo, _block); } /// @notice Called to get the current voting power delegated to a user /// @param userAddress User address /// @return Current voting power delegated to the user function delegatedToUser(address userAddress) public view override returns (uint256) { return delegatedToUserAt(userAddress, block.number); } /// @notice Called to get the delegate of the user at a specific block /// @param userAddress User address /// @param _block Block number /// @return Delegate of the user at the specific block function userDelegateAt( address userAddress, uint256 _block ) public view override returns (address) { return getAddressAt(users[userAddress].delegates, _block); } /// @notice Called to get the current delegate of the user /// @param userAddress User address /// @return Current delegate of the user function userDelegate(address userAddress) public view override returns (address) { return userDelegateAt(userAddress, block.number); } /// @notice Called to get the current locked tokens of the user /// @param userAddress User address /// @return locked Current locked tokens of the user function userLocked(address userAddress) public view override returns (uint256 locked) { Checkpoint[] storage _userShares = users[userAddress].shares; uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; uint256 oldestLockedEpoch = getOldestLockedEpoch(); uint256 indUserShares = _userShares.length; for ( uint256 indEpoch = currentEpoch; indEpoch >= oldestLockedEpoch; indEpoch-- ) { // The user has never staked at this point, we can exit early if (indUserShares == 0) { break; } Reward storage lockedReward = epochIndexToReward[indEpoch]; if (lockedReward.atBlock != 0) { for (; indUserShares > 0; indUserShares--) { Checkpoint storage userShare = _userShares[indUserShares - 1]; if (userShare.fromBlock <= lockedReward.atBlock) { locked += lockedReward.amount * userShare.value / lockedReward.totalSharesThen; break; } } } } } /// @notice Called to get the details of a user /// @param userAddress User address /// @return unstaked Amount of unstaked API3 tokens /// @return vesting Amount of API3 tokens locked by vesting /// @return unstakeAmount Amount scheduled to unstake /// @return unstakeShares Shares revoked to unstake /// @return unstakeScheduledFor Time unstaking is scheduled for /// @return lastDelegationUpdateTimestamp Time of last delegation update /// @return lastProposalTimestamp Time when the user made their most /// recent proposal function getUser(address userAddress) external view override returns ( uint256 unstaked, uint256 vesting, uint256 unstakeAmount, uint256 unstakeShares, uint256 unstakeScheduledFor, uint256 lastDelegationUpdateTimestamp, uint256 lastProposalTimestamp ) { User storage user = users[userAddress]; unstaked = user.unstaked; vesting = user.vesting; unstakeAmount = user.unstakeAmount; unstakeShares = user.unstakeShares; unstakeScheduledFor = user.unstakeScheduledFor; lastDelegationUpdateTimestamp = user.lastDelegationUpdateTimestamp; lastProposalTimestamp = user.lastProposalTimestamp; } /// @notice Called to get the value of a checkpoint array at a specific /// block using binary search /// @dev Adapted from /// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431 /// @param checkpoints Checkpoints array /// @param _block Block number for which the query is being made /// @return Value of the checkpoint array at the block function getValueAt( Checkpoint[] storage checkpoints, uint256 _block ) internal view returns (uint256) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length -1].fromBlock) return checkpoints[checkpoints.length - 1].value; if (_block < checkpoints[0].fromBlock) return 0; // Limit the search to the last 1024 elements if the value being // searched falls within that window uint min = 0; if ( checkpoints.length > 1024 && checkpoints[checkpoints.length - 1024].fromBlock < _block ) { min = checkpoints.length - 1024; } // Binary search of the value in the array uint max = checkpoints.length - 1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min].value; } /// @notice Called to get the value of an address-checkpoint array at a /// specific block using binary search /// @dev Adapted from /// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431 /// @param checkpoints Address-checkpoint array /// @param _block Block number for which the query is being made /// @return Value of the address-checkpoint array at the block function getAddressAt( AddressCheckpoint[] storage checkpoints, uint256 _block ) private view returns (address) { if (checkpoints.length == 0) return address(0); // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length -1].fromBlock) return checkpoints[checkpoints.length - 1]._address; if (_block < checkpoints[0].fromBlock) return address(0); // Limit the search to the last 1024 elements if the value being // searched falls within that window uint min = 0; if ( checkpoints.length > 1024 && checkpoints[checkpoints.length - 1024].fromBlock < _block ) { min = checkpoints.length - 1024; } // Binary search of the value in the array uint max = checkpoints.length - 1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock <= _block) { min = mid; } else { max = mid - 1; } } return checkpoints[min]._address; } /// @notice Called internally to get the index of the oldest epoch whose /// reward should be locked in the current epoch /// @return oldestLockedEpoch Index of the oldest epoch with locked rewards function getOldestLockedEpoch() internal view returns (uint256 oldestLockedEpoch) { uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; oldestLockedEpoch = currentEpoch - REWARD_VESTING_PERIOD + 1; if (oldestLockedEpoch < genesisEpoch + 1) { oldestLockedEpoch = genesisEpoch + 1; } } } // File contracts/interfaces/IRewardUtils.sol pragma solidity 0.8.4; interface IRewardUtils is IGetterUtils { event MintedReward( uint256 indexed epochIndex, uint256 amount, uint256 newApr, uint256 totalStake ); function mintReward() external; } // File contracts/RewardUtils.sol pragma solidity 0.8.4; /// @title Contract that implements reward payments abstract contract RewardUtils is GetterUtils, IRewardUtils { /// @notice Called to mint the staking reward /// @dev Skips past epochs for which rewards have not been paid for. /// Skips the reward payment if the pool is not authorized to mint tokens. /// Neither of these conditions will occur in practice. function mintReward() public override { uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; // This will be skipped in most cases because someone else will have // triggered the payment for this epoch if (epochIndexOfLastReward < currentEpoch) { if (api3Token.getMinterStatus(address(this))) { uint256 rewardAmount = totalStake * apr * EPOCH_LENGTH / 365 days / HUNDRED_PERCENT; assert(block.number <= MAX_UINT32); assert(rewardAmount <= MAX_UINT224); epochIndexToReward[currentEpoch] = Reward({ atBlock: uint32(block.number), amount: uint224(rewardAmount), totalSharesThen: totalShares(), totalStakeThen: totalStake }); api3Token.mint(address(this), rewardAmount); totalStake += rewardAmount; updateCurrentApr(); emit MintedReward( currentEpoch, rewardAmount, apr, totalStake ); } epochIndexOfLastReward = currentEpoch; } } /// @notice Updates the current APR /// @dev Called internally after paying out the reward function updateCurrentApr() internal { uint256 totalStakePercentage = totalStake * HUNDRED_PERCENT / api3Token.totalSupply(); if (totalStakePercentage > stakeTarget) { apr = apr > aprUpdateStep ? apr - aprUpdateStep : 0; } else { apr += aprUpdateStep; } if (apr > maxApr) { apr = maxApr; } else if (apr < minApr) { apr = minApr; } } } // File contracts/interfaces/IDelegationUtils.sol pragma solidity 0.8.4; interface IDelegationUtils is IRewardUtils { event Delegated( address indexed user, address indexed delegate, uint256 shares, uint256 totalDelegatedTo ); event Undelegated( address indexed user, address indexed delegate, uint256 shares, uint256 totalDelegatedTo ); event UpdatedDelegation( address indexed user, address indexed delegate, bool delta, uint256 shares, uint256 totalDelegatedTo ); function delegateVotingPower(address delegate) external; function undelegateVotingPower() external; } // File contracts/DelegationUtils.sol pragma solidity 0.8.4; /// @title Contract that implements voting power delegation abstract contract DelegationUtils is RewardUtils, IDelegationUtils { /// @notice Called by the user to delegate voting power /// @param delegate User address the voting power will be delegated to function delegateVotingPower(address delegate) external override { mintReward(); require( delegate != address(0) && delegate != msg.sender, "Pool: Invalid delegate" ); // Delegating users cannot use their voting power, so we are // verifying that the delegate is not currently delegating. However, // the delegate may delegate after they have been delegated to. require( userDelegate(delegate) == address(0), "Pool: Delegate is delegating" ); User storage user = users[msg.sender]; // Do not allow frequent delegation updates as that can be used to spam // proposals require( user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp, "Pool: Updated delegate recently" ); user.lastDelegationUpdateTimestamp = block.timestamp; uint256 userShares = userShares(msg.sender); require( userShares != 0, "Pool: Have no shares to delegate" ); address previousDelegate = userDelegate(msg.sender); require( previousDelegate != delegate, "Pool: Already delegated" ); if (previousDelegate != address(0)) { // Need to revoke previous delegation updateCheckpointArray( users[previousDelegate].delegatedTo, delegatedToUser(previousDelegate) - userShares ); } // Assign the new delegation uint256 delegatedToUpdate = delegatedToUser(delegate) + userShares; updateCheckpointArray( users[delegate].delegatedTo, delegatedToUpdate ); // Record the new delegate for the user updateAddressCheckpointArray( user.delegates, delegate ); emit Delegated( msg.sender, delegate, userShares, delegatedToUpdate ); } /// @notice Called by the user to undelegate voting power function undelegateVotingPower() external override { mintReward(); User storage user = users[msg.sender]; address previousDelegate = userDelegate(msg.sender); require( previousDelegate != address(0), "Pool: Not delegated" ); require( user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp, "Pool: Updated delegate recently" ); user.lastDelegationUpdateTimestamp = block.timestamp; uint256 userShares = userShares(msg.sender); uint256 delegatedToUpdate = delegatedToUser(previousDelegate) - userShares; updateCheckpointArray( users[previousDelegate].delegatedTo, delegatedToUpdate ); updateAddressCheckpointArray( user.delegates, address(0) ); emit Undelegated( msg.sender, previousDelegate, userShares, delegatedToUpdate ); } /// @notice Called internally when the user shares are updated to update /// the delegated voting power /// @dev User shares only get updated while staking or scheduling unstaking /// @param shares Amount of shares that will be added/removed /// @param delta Whether the shares will be added/removed (add for `true`, /// and vice versa) function updateDelegatedVotingPower( uint256 shares, bool delta ) internal { address delegate = userDelegate(msg.sender); if (delegate == address(0)) { return; } uint256 currentDelegatedTo = delegatedToUser(delegate); uint256 delegatedToUpdate = delta ? currentDelegatedTo + shares : currentDelegatedTo - shares; updateCheckpointArray( users[delegate].delegatedTo, delegatedToUpdate ); emit UpdatedDelegation( msg.sender, delegate, delta, shares, delegatedToUpdate ); } } // File contracts/interfaces/ITransferUtils.sol pragma solidity 0.8.4; interface ITransferUtils is IDelegationUtils{ event Deposited( address indexed user, uint256 amount, uint256 userUnstaked ); event Withdrawn( address indexed user, uint256 amount, uint256 userUnstaked ); event CalculatingUserLocked( address indexed user, uint256 nextIndEpoch, uint256 oldestLockedEpoch ); event CalculatedUserLocked( address indexed user, uint256 amount ); function depositRegular(uint256 amount) external; function withdrawRegular(uint256 amount) external; function precalculateUserLocked( address userAddress, uint256 noEpochsPerIteration ) external returns (bool finished); function withdrawPrecalculated(uint256 amount) external; } // File contracts/TransferUtils.sol pragma solidity 0.8.4; /// @title Contract that implements token transfer functionality abstract contract TransferUtils is DelegationUtils, ITransferUtils { /// @notice Called by the user to deposit tokens /// @dev The user should approve the pool to spend at least `amount` tokens /// before calling this. /// The method is named `depositRegular()` to prevent potential confusion. /// See `deposit()` for more context. /// @param amount Amount to be deposited function depositRegular(uint256 amount) public override { mintReward(); uint256 unstakedUpdate = users[msg.sender].unstaked + amount; users[msg.sender].unstaked = unstakedUpdate; // Should never return false because the API3 token uses the // OpenZeppelin implementation assert(api3Token.transferFrom(msg.sender, address(this), amount)); emit Deposited( msg.sender, amount, unstakedUpdate ); } /// @notice Called by the user to withdraw tokens to their wallet /// @dev The user should call `userLocked()` beforehand to ensure that /// they have at least `amount` unlocked tokens to withdraw. /// The method is named `withdrawRegular()` to be consistent with the name /// `depositRegular()`. See `depositRegular()` for more context. /// @param amount Amount to be withdrawn function withdrawRegular(uint256 amount) public override { mintReward(); withdraw(amount, userLocked(msg.sender)); } /// @notice Called to calculate the locked tokens of a user by making /// multiple transactions /// @dev If the user updates their `user.shares` by staking/unstaking too /// frequently (50+/week) in the last `REWARD_VESTING_PERIOD`, the /// `userLocked()` call gas cost may exceed the block gas limit. In that /// case, the user may call this method multiple times to have their locked /// tokens calculated and use `withdrawPrecalculated()` to withdraw. /// @param userAddress User address /// @param noEpochsPerIteration Number of epochs per iteration /// @return finished Calculation has finished in this call function precalculateUserLocked( address userAddress, uint256 noEpochsPerIteration ) external override returns (bool finished) { mintReward(); require( noEpochsPerIteration > 0, "Pool: Zero iteration window" ); uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; LockedCalculation storage lockedCalculation = userToLockedCalculation[userAddress]; // Reset the state if there was no calculation made in this epoch if (lockedCalculation.initialIndEpoch != currentEpoch) { lockedCalculation.initialIndEpoch = currentEpoch; lockedCalculation.nextIndEpoch = currentEpoch; lockedCalculation.locked = 0; } uint256 indEpoch = lockedCalculation.nextIndEpoch; uint256 locked = lockedCalculation.locked; uint256 oldestLockedEpoch = getOldestLockedEpoch(); for (; indEpoch >= oldestLockedEpoch; indEpoch--) { if (lockedCalculation.nextIndEpoch >= indEpoch + noEpochsPerIteration) { lockedCalculation.nextIndEpoch = indEpoch; lockedCalculation.locked = locked; emit CalculatingUserLocked( userAddress, indEpoch, oldestLockedEpoch ); return false; } Reward storage lockedReward = epochIndexToReward[indEpoch]; if (lockedReward.atBlock != 0) { uint256 userSharesThen = userSharesAt(userAddress, lockedReward.atBlock); locked += lockedReward.amount * userSharesThen / lockedReward.totalSharesThen; } } lockedCalculation.nextIndEpoch = indEpoch; lockedCalculation.locked = locked; emit CalculatedUserLocked(userAddress, locked); return true; } /// @notice Called by the user to withdraw after their locked token amount /// is calculated with repeated calls to `precalculateUserLocked()` /// @dev Only use `precalculateUserLocked()` and this method if /// `withdrawRegular()` hits the block gas limit /// @param amount Amount to be withdrawn function withdrawPrecalculated(uint256 amount) external override { mintReward(); uint256 currentEpoch = block.timestamp / EPOCH_LENGTH; LockedCalculation storage lockedCalculation = userToLockedCalculation[msg.sender]; require( lockedCalculation.initialIndEpoch == currentEpoch, "Pool: Calculation not up to date" ); require( lockedCalculation.nextIndEpoch < getOldestLockedEpoch(), "Pool: Calculation not complete" ); withdraw(amount, lockedCalculation.locked); } /// @notice Called internally after the amount of locked tokens of the user /// is determined /// @param amount Amount to be withdrawn /// @param userLocked Amount of locked tokens of the user function withdraw( uint256 amount, uint256 userLocked ) private { User storage user = users[msg.sender]; // Check if the user has `amount` unlocked tokens to withdraw uint256 lockedAndVesting = userLocked + user.vesting; uint256 userTotalFunds = user.unstaked + userStake(msg.sender); require( userTotalFunds >= lockedAndVesting + amount, "Pool: Not enough unlocked funds" ); require( user.unstaked >= amount, "Pool: Not enough unstaked funds" ); // Carry on with the withdrawal uint256 unstakedUpdate = user.unstaked - amount; user.unstaked = unstakedUpdate; // Should never return false because the API3 token uses the // OpenZeppelin implementation assert(api3Token.transfer(msg.sender, amount)); emit Withdrawn( msg.sender, amount, unstakedUpdate ); } } // File contracts/interfaces/IStakeUtils.sol pragma solidity 0.8.4; interface IStakeUtils is ITransferUtils{ event Staked( address indexed user, uint256 amount, uint256 mintedShares, uint256 userUnstaked, uint256 userShares, uint256 totalShares, uint256 totalStake ); event ScheduledUnstake( address indexed user, uint256 amount, uint256 shares, uint256 scheduledFor, uint256 userShares ); event Unstaked( address indexed user, uint256 amount, uint256 userUnstaked, uint256 totalShares, uint256 totalStake ); function stake(uint256 amount) external; function depositAndStake(uint256 amount) external; function scheduleUnstake(uint256 amount) external; function unstake(address userAddress) external returns (uint256); function unstakeAndWithdraw() external; } // File contracts/StakeUtils.sol pragma solidity 0.8.4; /// @title Contract that implements staking functionality abstract contract StakeUtils is TransferUtils, IStakeUtils { /// @notice Called to stake tokens to receive pools in the share /// @param amount Amount of tokens to stake function stake(uint256 amount) public override { mintReward(); User storage user = users[msg.sender]; require( user.unstaked >= amount, "Pool: Amount exceeds unstaked" ); uint256 userUnstakedUpdate = user.unstaked - amount; user.unstaked = userUnstakedUpdate; uint256 totalSharesNow = totalShares(); uint256 sharesToMint = amount * totalSharesNow / totalStake; uint256 userSharesUpdate = userShares(msg.sender) + sharesToMint; updateCheckpointArray( user.shares, userSharesUpdate ); uint256 totalSharesUpdate = totalSharesNow + sharesToMint; updateCheckpointArray( poolShares, totalSharesUpdate ); totalStake += amount; updateDelegatedVotingPower(sharesToMint, true); emit Staked( msg.sender, amount, sharesToMint, userUnstakedUpdate, userSharesUpdate, totalSharesUpdate, totalStake ); } /// @notice Convenience method to deposit and stake in a single transaction /// @param amount Amount to be deposited and staked function depositAndStake(uint256 amount) external override { depositRegular(amount); stake(amount); } /// @notice Called by the user to schedule unstaking of their tokens /// @dev While scheduling an unstake, `shares` get deducted from the user, /// meaning that they will not receive rewards or voting power for them any /// longer. /// At unstaking-time, the user unstakes either the amount of tokens /// scheduled to unstake, or the amount of tokens `shares` corresponds to /// at unstaking-time, whichever is smaller. This corresponds to tokens /// being scheduled to be unstaked not receiving any rewards, but being /// subject to claim payouts. /// In the instance that a claim has been paid out before an unstaking is /// executed, the user may potentially receive rewards during /// `unstakeWaitPeriod` (but not if there has not been a claim payout) but /// the amount of tokens that they can unstake will not be able to exceed /// the amount they scheduled the unstaking for. /// @param amount Amount of tokens scheduled to unstake function scheduleUnstake(uint256 amount) external override { mintReward(); uint256 userSharesNow = userShares(msg.sender); uint256 totalSharesNow = totalShares(); uint256 userStaked = userSharesNow * totalStake / totalSharesNow; require( userStaked >= amount, "Pool: Amount exceeds staked" ); User storage user = users[msg.sender]; require( user.unstakeScheduledFor == 0, "Pool: Unexecuted unstake exists" ); uint256 sharesToUnstake = amount * totalSharesNow / totalStake; // This will only happen if the user wants to schedule an unstake for a // few Wei require(sharesToUnstake > 0, "Pool: Unstake amount too small"); uint256 unstakeScheduledFor = block.timestamp + unstakeWaitPeriod; user.unstakeScheduledFor = unstakeScheduledFor; user.unstakeAmount = amount; user.unstakeShares = sharesToUnstake; uint256 userSharesUpdate = userSharesNow - sharesToUnstake; updateCheckpointArray( user.shares, userSharesUpdate ); updateDelegatedVotingPower(sharesToUnstake, false); emit ScheduledUnstake( msg.sender, amount, sharesToUnstake, unstakeScheduledFor, userSharesUpdate ); } /// @notice Called to execute a pre-scheduled unstake /// @dev Anyone can execute a matured unstake. This is to allow the user to /// use bots, etc. to execute their unstaking as soon as possible. /// @param userAddress User address /// @return Amount of tokens that are unstaked function unstake(address userAddress) public override returns (uint256) { mintReward(); User storage user = users[userAddress]; require( user.unstakeScheduledFor != 0, "Pool: No unstake scheduled" ); require( user.unstakeScheduledFor < block.timestamp, "Pool: Unstake not mature yet" ); uint256 totalShares = totalShares(); uint256 unstakeAmount = user.unstakeAmount; uint256 unstakeAmountByShares = user.unstakeShares * totalStake / totalShares; // If there was a claim payout in between the scheduling and the actual // unstake then the amount might be lower than expected at scheduling // time if (unstakeAmount > unstakeAmountByShares) { unstakeAmount = unstakeAmountByShares; } uint256 userUnstakedUpdate = user.unstaked + unstakeAmount; user.unstaked = userUnstakedUpdate; uint256 totalSharesUpdate = totalShares - user.unstakeShares; updateCheckpointArray( poolShares, totalSharesUpdate ); totalStake -= unstakeAmount; user.unstakeAmount = 0; user.unstakeShares = 0; user.unstakeScheduledFor = 0; emit Unstaked( userAddress, unstakeAmount, userUnstakedUpdate, totalSharesUpdate, totalStake ); return unstakeAmount; } /// @notice Convenience method to execute an unstake and withdraw to the /// user's wallet in a single transaction /// @dev The withdrawal will revert if the user has less than /// `unstakeAmount` tokens that are withdrawable function unstakeAndWithdraw() external override { withdrawRegular(unstake(msg.sender)); } } // File contracts/interfaces/IClaimUtils.sol pragma solidity 0.8.4; interface IClaimUtils is IStakeUtils { event PaidOutClaim( address indexed recipient, uint256 amount, uint256 totalStake ); function payOutClaim( address recipient, uint256 amount ) external; } // File contracts/ClaimUtils.sol pragma solidity 0.8.4; /// @title Contract that implements the insurance claim payout functionality abstract contract ClaimUtils is StakeUtils, IClaimUtils { /// @dev Reverts if the caller is not a claims manager modifier onlyClaimsManager() { require( claimsManagerStatus[msg.sender], "Pool: Caller not claims manager" ); _; } /// @notice Called by a claims manager to pay out an insurance claim /// @dev The claims manager is a trusted contract that is allowed to /// withdraw as many tokens as it wants from the pool to pay out insurance /// claims. Any kind of limiting logic (e.g., maximum amount of tokens that /// can be withdrawn) is implemented at its end and is out of the scope of /// this contract. /// This will revert if the pool does not have enough staked funds. /// @param recipient Recipient of the claim /// @param amount Amount of tokens that will be paid out function payOutClaim( address recipient, uint256 amount ) external override onlyClaimsManager() { mintReward(); // totalStake should not go lower than 1 require( totalStake > amount, "Pool: Amount exceeds total stake" ); totalStake -= amount; // Should never return false because the API3 token uses the // OpenZeppelin implementation assert(api3Token.transfer(recipient, amount)); emit PaidOutClaim( recipient, amount, totalStake ); } } // File contracts/interfaces/ITimelockUtils.sol pragma solidity 0.8.4; interface ITimelockUtils is IClaimUtils { event DepositedByTimelockManager( address indexed user, uint256 amount, uint256 userUnstaked ); event DepositedVesting( address indexed user, uint256 amount, uint256 start, uint256 end, uint256 userUnstaked, uint256 userVesting ); event VestedTimelock( address indexed user, uint256 amount, uint256 userVesting ); function deposit( address source, uint256 amount, address userAddress ) external; function depositWithVesting( address source, uint256 amount, address userAddress, uint256 releaseStart, uint256 releaseEnd ) external; function updateTimelockStatus(address userAddress) external; } // File contracts/TimelockUtils.sol pragma solidity 0.8.4; /// @title Contract that implements vesting functionality /// @dev The TimelockManager contract interfaces with this contract to transfer /// API3 tokens that are locked under a vesting schedule. /// This contract keeps its own type definitions, event declarations and state /// variables for them to be easier to remove for a subDAO where they will /// likely not be used. abstract contract TimelockUtils is ClaimUtils, ITimelockUtils { struct Timelock { uint256 totalAmount; uint256 remainingAmount; uint256 releaseStart; uint256 releaseEnd; } /// @notice Maps user addresses to timelocks /// @dev This implies that a user cannot have multiple timelocks /// transferred from the TimelockManager contract. This is acceptable /// because TimelockManager is implemented in a way to not allow multiple /// timelocks per user. mapping(address => Timelock) public userToTimelock; /// @notice Called by the TimelockManager contract to deposit tokens on /// behalf of a user /// @dev This method is only usable by `TimelockManager.sol`. /// It is named as `deposit()` and not `depositAsTimelockManager()` for /// example, because the TimelockManager is already deployed and expects /// the `deposit(address,uint256,address)` interface. /// @param source Token transfer source /// @param amount Amount to be deposited /// @param userAddress User that the tokens will be deposited for function deposit( address source, uint256 amount, address userAddress ) external override { require( msg.sender == timelockManager, "Pool: Caller not TimelockManager" ); uint256 unstakedUpdate = users[userAddress].unstaked + amount; users[userAddress].unstaked = unstakedUpdate; // Should never return false because the API3 token uses the // OpenZeppelin implementation assert(api3Token.transferFrom(source, address(this), amount)); emit DepositedByTimelockManager( userAddress, amount, unstakedUpdate ); } /// @notice Called by the TimelockManager contract to deposit tokens on /// behalf of a user on a linear vesting schedule /// @dev Refer to `TimelockManager.sol` to see how this is used /// @param source Token source /// @param amount Token amount /// @param userAddress Address of the user who will receive the tokens /// @param releaseStart Vesting schedule starting time /// @param releaseEnd Vesting schedule ending time function depositWithVesting( address source, uint256 amount, address userAddress, uint256 releaseStart, uint256 releaseEnd ) external override { require( msg.sender == timelockManager, "Pool: Caller not TimelockManager" ); require( userToTimelock[userAddress].remainingAmount == 0, "Pool: User has active timelock" ); require( releaseEnd > releaseStart, "Pool: Timelock start after end" ); require( amount != 0, "Pool: Timelock amount zero" ); uint256 unstakedUpdate = users[userAddress].unstaked + amount; users[userAddress].unstaked = unstakedUpdate; uint256 vestingUpdate = users[userAddress].vesting + amount; users[userAddress].vesting = vestingUpdate; userToTimelock[userAddress] = Timelock({ totalAmount: amount, remainingAmount: amount, releaseStart: releaseStart, releaseEnd: releaseEnd }); // Should never return false because the API3 token uses the // OpenZeppelin implementation assert(api3Token.transferFrom(source, address(this), amount)); emit DepositedVesting( userAddress, amount, releaseStart, releaseEnd, unstakedUpdate, vestingUpdate ); } /// @notice Called to release tokens vested by the timelock /// @param userAddress Address of the user whose timelock status will be /// updated function updateTimelockStatus(address userAddress) external override { Timelock storage timelock = userToTimelock[userAddress]; require( block.timestamp > timelock.releaseStart, "Pool: Release not started yet" ); require( timelock.remainingAmount > 0, "Pool: Timelock already released" ); uint256 totalUnlocked; if (block.timestamp >= timelock.releaseEnd) { totalUnlocked = timelock.totalAmount; } else { uint256 passedTime = block.timestamp - timelock.releaseStart; uint256 totalTime = timelock.releaseEnd - timelock.releaseStart; totalUnlocked = timelock.totalAmount * passedTime / totalTime; } uint256 previouslyUnlocked = timelock.totalAmount - timelock.remainingAmount; uint256 newlyUnlocked = totalUnlocked - previouslyUnlocked; User storage user = users[userAddress]; uint256 vestingUpdate = user.vesting - newlyUnlocked; user.vesting = vestingUpdate; timelock.remainingAmount -= newlyUnlocked; emit VestedTimelock( userAddress, newlyUnlocked, vestingUpdate ); } } // File contracts/interfaces/IApi3Pool.sol pragma solidity 0.8.4; interface IApi3Pool is ITimelockUtils { } // File contracts/Api3Pool.sol pragma solidity 0.8.4; /// @title API3 pool contract /// @notice Users can stake API3 tokens at the pool contract to be granted /// shares. These shares are exposed to the Aragon-based DAO, giving the user /// voting power at the DAO. Staking pays out weekly rewards that get unlocked /// after a year, and staked funds are used to collateralize an insurance /// product that is outside the scope of this contract. /// @dev Functionalities of the contract are distributed to files that form a /// chain of inheritance: /// (1) Api3Pool.sol /// (2) TimelockUtils.sol /// (3) ClaimUtils.sol /// (4) StakeUtils.sol /// (5) TransferUtils.sol /// (6) DelegationUtils.sol /// (7) RewardUtils.sol /// (8) GetterUtils.sol /// (9) StateUtils.sol contract Api3Pool is TimelockUtils, IApi3Pool { /// @param api3TokenAddress API3 token contract address /// @param timelockManagerAddress Timelock manager contract address constructor( address api3TokenAddress, address timelockManagerAddress ) StateUtils( api3TokenAddress, timelockManagerAddress ) {} }
@title Contract that implements vesting functionality @dev The TimelockManager contract interfaces with this contract to transfer API3 tokens that are locked under a vesting schedule. This contract keeps its own type definitions, event declarations and state variables for them to be easier to remove for a subDAO where they will likely not be used.
abstract contract TimelockUtils is ClaimUtils, ITimelockUtils { struct Timelock { uint256 totalAmount; uint256 remainingAmount; uint256 releaseStart; uint256 releaseEnd; } mapping(address => Timelock) public userToTimelock; function deposit( address source, uint256 amount, address userAddress ) external override { require( msg.sender == timelockManager, "Pool: Caller not TimelockManager" ); uint256 unstakedUpdate = users[userAddress].unstaked + amount; users[userAddress].unstaked = unstakedUpdate; assert(api3Token.transferFrom(source, address(this), amount)); emit DepositedByTimelockManager( userAddress, amount, unstakedUpdate ); } function depositWithVesting( address source, uint256 amount, address userAddress, uint256 releaseStart, uint256 releaseEnd ) external override { require( msg.sender == timelockManager, "Pool: Caller not TimelockManager" ); require( userToTimelock[userAddress].remainingAmount == 0, "Pool: User has active timelock" ); require( releaseEnd > releaseStart, "Pool: Timelock start after end" ); require( amount != 0, "Pool: Timelock amount zero" ); uint256 unstakedUpdate = users[userAddress].unstaked + amount; users[userAddress].unstaked = unstakedUpdate; uint256 vestingUpdate = users[userAddress].vesting + amount; users[userAddress].vesting = vestingUpdate; userToTimelock[userAddress] = Timelock({ totalAmount: amount, remainingAmount: amount, releaseStart: releaseStart, releaseEnd: releaseEnd }); emit DepositedVesting( userAddress, amount, releaseStart, releaseEnd, unstakedUpdate, vestingUpdate ); } function depositWithVesting( address source, uint256 amount, address userAddress, uint256 releaseStart, uint256 releaseEnd ) external override { require( msg.sender == timelockManager, "Pool: Caller not TimelockManager" ); require( userToTimelock[userAddress].remainingAmount == 0, "Pool: User has active timelock" ); require( releaseEnd > releaseStart, "Pool: Timelock start after end" ); require( amount != 0, "Pool: Timelock amount zero" ); uint256 unstakedUpdate = users[userAddress].unstaked + amount; users[userAddress].unstaked = unstakedUpdate; uint256 vestingUpdate = users[userAddress].vesting + amount; users[userAddress].vesting = vestingUpdate; userToTimelock[userAddress] = Timelock({ totalAmount: amount, remainingAmount: amount, releaseStart: releaseStart, releaseEnd: releaseEnd }); emit DepositedVesting( userAddress, amount, releaseStart, releaseEnd, unstakedUpdate, vestingUpdate ); } assert(api3Token.transferFrom(source, address(this), amount)); function updateTimelockStatus(address userAddress) external override { Timelock storage timelock = userToTimelock[userAddress]; require( block.timestamp > timelock.releaseStart, "Pool: Release not started yet" ); require( timelock.remainingAmount > 0, "Pool: Timelock already released" ); uint256 totalUnlocked; if (block.timestamp >= timelock.releaseEnd) { totalUnlocked = timelock.totalAmount; } else { uint256 passedTime = block.timestamp - timelock.releaseStart; uint256 totalTime = timelock.releaseEnd - timelock.releaseStart; totalUnlocked = timelock.totalAmount * passedTime / totalTime; } uint256 previouslyUnlocked = timelock.totalAmount - timelock.remainingAmount; uint256 newlyUnlocked = totalUnlocked - previouslyUnlocked; User storage user = users[userAddress]; uint256 vestingUpdate = user.vesting - newlyUnlocked; user.vesting = vestingUpdate; timelock.remainingAmount -= newlyUnlocked; emit VestedTimelock( userAddress, newlyUnlocked, vestingUpdate ); } function updateTimelockStatus(address userAddress) external override { Timelock storage timelock = userToTimelock[userAddress]; require( block.timestamp > timelock.releaseStart, "Pool: Release not started yet" ); require( timelock.remainingAmount > 0, "Pool: Timelock already released" ); uint256 totalUnlocked; if (block.timestamp >= timelock.releaseEnd) { totalUnlocked = timelock.totalAmount; } else { uint256 passedTime = block.timestamp - timelock.releaseStart; uint256 totalTime = timelock.releaseEnd - timelock.releaseStart; totalUnlocked = timelock.totalAmount * passedTime / totalTime; } uint256 previouslyUnlocked = timelock.totalAmount - timelock.remainingAmount; uint256 newlyUnlocked = totalUnlocked - previouslyUnlocked; User storage user = users[userAddress]; uint256 vestingUpdate = user.vesting - newlyUnlocked; user.vesting = vestingUpdate; timelock.remainingAmount -= newlyUnlocked; emit VestedTimelock( userAddress, newlyUnlocked, vestingUpdate ); } function updateTimelockStatus(address userAddress) external override { Timelock storage timelock = userToTimelock[userAddress]; require( block.timestamp > timelock.releaseStart, "Pool: Release not started yet" ); require( timelock.remainingAmount > 0, "Pool: Timelock already released" ); uint256 totalUnlocked; if (block.timestamp >= timelock.releaseEnd) { totalUnlocked = timelock.totalAmount; } else { uint256 passedTime = block.timestamp - timelock.releaseStart; uint256 totalTime = timelock.releaseEnd - timelock.releaseStart; totalUnlocked = timelock.totalAmount * passedTime / totalTime; } uint256 previouslyUnlocked = timelock.totalAmount - timelock.remainingAmount; uint256 newlyUnlocked = totalUnlocked - previouslyUnlocked; User storage user = users[userAddress]; uint256 vestingUpdate = user.vesting - newlyUnlocked; user.vesting = vestingUpdate; timelock.remainingAmount -= newlyUnlocked; emit VestedTimelock( userAddress, newlyUnlocked, vestingUpdate ); } }
2,456,856
[ 1, 8924, 716, 4792, 331, 10100, 14176, 225, 1021, 12652, 292, 975, 1318, 6835, 7349, 598, 333, 6835, 358, 7412, 1491, 23, 2430, 716, 854, 8586, 3613, 279, 331, 10100, 4788, 18, 1220, 6835, 20948, 2097, 4953, 618, 6377, 16, 871, 12312, 471, 919, 3152, 364, 2182, 358, 506, 15857, 358, 1206, 364, 279, 720, 18485, 1625, 2898, 903, 10374, 486, 506, 1399, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 12652, 292, 975, 1989, 353, 18381, 1989, 16, 467, 10178, 292, 975, 1989, 288, 203, 203, 565, 1958, 12652, 292, 975, 288, 203, 3639, 2254, 5034, 2078, 6275, 31, 203, 3639, 2254, 5034, 4463, 6275, 31, 203, 3639, 2254, 5034, 3992, 1685, 31, 203, 3639, 2254, 5034, 3992, 1638, 31, 203, 565, 289, 203, 203, 203, 565, 2874, 12, 2867, 516, 12652, 292, 975, 13, 1071, 729, 774, 10178, 292, 975, 31, 203, 565, 445, 443, 1724, 12, 203, 3639, 1758, 1084, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 729, 1887, 203, 3639, 262, 203, 3639, 3903, 203, 3639, 3849, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 1658, 292, 975, 1318, 16, 203, 5411, 315, 2864, 30, 20646, 486, 12652, 292, 975, 1318, 6, 203, 5411, 11272, 203, 3639, 2254, 5034, 640, 334, 9477, 1891, 273, 3677, 63, 1355, 1887, 8009, 23412, 9477, 397, 3844, 31, 203, 3639, 3677, 63, 1355, 1887, 8009, 23412, 9477, 273, 640, 334, 9477, 1891, 31, 203, 3639, 1815, 12, 2425, 23, 1345, 18, 13866, 1265, 12, 3168, 16, 1758, 12, 2211, 3631, 3844, 10019, 203, 3639, 3626, 4019, 538, 16261, 858, 10178, 292, 975, 1318, 12, 203, 5411, 729, 1887, 16, 203, 5411, 3844, 16, 203, 5411, 640, 334, 9477, 1891, 203, 5411, 11272, 203, 565, 289, 203, 203, 565, 445, 443, 1724, 1190, 58, 10100, 12, 203, 3639, 1758, 1084, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 729, 1887, 16, 203, 3639, 2254, 2 ]
./full_match/4/0x2D7b14B467A795B177bEEbf51CBd84d81876DB2a/sources/contracts/1_Storage.sol
Modified by Standard Developers from SushiRoll Contract by Sushiswap developers BarrelRoll helps your migrate your existing dex LP tokens to Standard DEX LTR ones
contract BarrelRoll { using SafeERC20 for IERC20; IUniswapV2Router01 public oldRouter; IUniswapV2Router01 public router; address setter; constructor(IUniswapV2Router01 _oldRouter, IUniswapV2Router01 _router, address _setter) public { oldRouter = _oldRouter; router = _router; setter = _setter; } function migrateWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB)); pair.permit(msg.sender, address(this), liquidity, deadline, v, r, s); migrate(tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline); } function migrate( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) public { require(deadline >= block.timestamp, 'Standard DEX: EXPIRED'); (uint256 amountA, uint256 amountB) = removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline ); (uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB); if (amountA > pooledAmountA) { IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA); } if (amountB > pooledAmountB) { IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB); } } function migrate( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) public { require(deadline >= block.timestamp, 'Standard DEX: EXPIRED'); (uint256 amountA, uint256 amountB) = removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline ); (uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB); if (amountA > pooledAmountA) { IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA); } if (amountB > pooledAmountB) { IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB); } } function migrate( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) public { require(deadline >= block.timestamp, 'Standard DEX: EXPIRED'); (uint256 amountA, uint256 amountB) = removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline ); (uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB); if (amountA > pooledAmountA) { IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA); } if (amountB > pooledAmountB) { IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB); } } function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB)); pair.transferFrom(msg.sender, address(pair), liquidity); (uint256 amount0, uint256 amount1) = pair.burn(address(this)); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'BarrelRoll: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'BarrelRoll: INSUFFICIENT_B_AMOUNT'); } function pairForOldRouter(address tokenA, address tokenB) public view returns (address pair) { (address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', oldRouter.factory(), keccak256(abi.encodePacked(token0, token1)), )))); } function test(address tokenA, address tokenB, bytes32 initCode) public view returns (address pair) { (address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', oldRouter.factory(), keccak256(abi.encodePacked(token0, token1)), )))); } function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint amountA, uint amountB) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired); address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB); IERC20(tokenA).safeTransfer(pair, amountA); IERC20(tokenB).safeTransfer(pair, amountB); IUniswapV2Pair(pair).mint(msg.sender); } function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); if (factory.getPair(tokenA, tokenB) == address(0)) { factory.createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); if (factory.getPair(tokenA, tokenB) == address(0)) { factory.createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); if (factory.getPair(tokenA, tokenB) == address(0)) { factory.createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } } else { function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); if (factory.getPair(tokenA, tokenB) == address(0)) { factory.createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } } else { }
13,298,168
[ 1, 4575, 635, 8263, 1505, 8250, 414, 628, 348, 1218, 77, 24194, 13456, 635, 348, 1218, 291, 91, 438, 21701, 16654, 2878, 24194, 21814, 3433, 13187, 3433, 2062, 302, 338, 511, 52, 2430, 358, 8263, 2030, 60, 511, 4349, 5945, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 16654, 2878, 24194, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 1611, 1071, 1592, 8259, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 1611, 1071, 4633, 31, 203, 565, 1758, 7794, 31, 203, 203, 203, 565, 3885, 12, 45, 984, 291, 91, 438, 58, 22, 8259, 1611, 389, 1673, 8259, 16, 467, 984, 291, 91, 438, 58, 22, 8259, 1611, 389, 10717, 16, 1758, 389, 18062, 13, 1071, 288, 203, 3639, 1592, 8259, 273, 389, 1673, 8259, 31, 203, 3639, 4633, 273, 389, 10717, 31, 203, 3639, 7794, 273, 389, 18062, 31, 203, 565, 289, 203, 203, 565, 445, 13187, 1190, 9123, 305, 12, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 16, 203, 3639, 2254, 5034, 4501, 372, 24237, 16, 203, 3639, 2254, 5034, 3844, 2192, 267, 16, 203, 3639, 2254, 5034, 3844, 38, 2930, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 1071, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 4154, 3082, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 6017, 1290, 7617, 8259, 12, 2316, 37, 16, 1147, 38, 10019, 203, 3639, 3082, 18, 457, 1938, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 4501, 372, 24237, 16, 14096, 16, 331, 16, 436, 16, 272, 1769, 203, 203, 3639, 13187, 12, 2316, 2 ]
pragma solidity ^0.4.9; //import "./Receiver_Interface.sol"; contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } //import "./ERC223_Interface.sol"; contract ERC223 { uint public totalSupply; function balanceOf(address who) public view returns (uint); function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } /** * ERC223 token by Dexaran * * https://github.com/Dexaran/ERC223-token-standard */ /* https://github.com/LykkeCity/EthereumApiDotNetCore/blob/master/src/ContractBuilder/contracts/token/SafeMath.sol */ contract SafeMath { uint256 constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; function safeAdd(uint256 x, uint256 y) pure internal returns (uint256 z) { if (x > MAX_UINT256 - y) revert(); return x + y; } function safeSub(uint256 x, uint256 y) pure internal returns (uint256 z) { if (x < y) revert(); return x - y; } function safeMul(uint256 x, uint256 y) pure internal returns (uint256 z) { if (y == 0) return 0; if (x > MAX_UINT256 / y) revert(); return x * y; } } contract HotPotatoToken is ERC223, SafeMath { mapping(address => uint) balances; string public name = "Hot Potato Token v0"; string public symbol = "HPT"; uint8 public decimals = 18; uint256 public totalSupply = 0; function HotPotatoToken() public { //balances[msg.sender]=totalSupply; burnTime=block.timestamp+60*60; burnTarget=msg.sender; } // Function to access name of token . function name() public view returns (string _name) { return name; } // Function to access symbol of token . function symbol() public view returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() public view returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } // Primary Hot Potato Code uint burnTime; uint hptSupply; address burnTarget; address[] hodlers; // array of all hodlers mapping (address=>uint) hodlIndex; // where the hodlers at? // TODO allow burner to move potato function detonatePotato() public returns (bool){ // is it time to burn someone? if(block.timestamp < burnTime)return; // ooo too bad hptSupply=safeSub(hptSupply,balances[burnTarget]); balances[burnTarget]=0; delHodler(hodlIndex[burnTarget]); burnTime=block.timestamp+60*60; } function movePotato() public returns (bool){ // only the target should be able to move potato if(msg.sender!=burnTarget) return false; burnTarget = hodlers[(hodlIndex[burnTarget]+1)%hodlers.length]; return true; } function addHodler(address hodler) private returns (bool){ if(hodlIndex[hodler]!=0)return false; // make sure it's not there already hodlIndex[hodler] = hodlers.length; //hodler should be last line hodlers.push(hodler); // add hodler to hodlers return true; } function delHodler(uint index) private returns (bool){ if(index > hodlers.length)return false; hodlIndex[hodlers[index]]=0; // delete from mapping delete hodlers[index]; // delete from array hodlers[index]=hodlers[hodlers.length-1]; // move last element to open slot delete hodlers[hodlers.length-1]; // trim entry from the sender\ hodlers.length=hodlers.length-1; hodlIndex[hodlers[index]]=index; // reindex the moved hodler return true; } function buyHPT() public payable returns (bool){ uint exchange=1000; if(address(this).balance==0 || hptSupply==0)exchange = 1000; else exchange=hptSupply/(address(this).balance-msg.value); balances[msg.sender]=safeAdd(balances[msg.sender],safeMul(msg.value,exchange)); hptSupply=safeAdd(hptSupply,safeMul(msg.value,exchange)); // increase the supply addHodler(msg.sender); // just in case this this the first time return true; } function sellHPT() public returns (bool){ if(balances[msg.sender]==0)return false; // nice try.. hptSupply=safeSub(hptSupply,balances[msg.sender]); msg.sender.transfer(balances[msg.sender]/getExchange()); balances[msg.sender]=0; delHodler(hodlIndex[msg.sender]); return true; } function getExchange() constant public returns (uint) { if(address(this).balance==0 || hptSupply==0)return 1000; return hptSupply/address(this).balance; } function getStats() constant public returns(uint supply, uint totalBalance, uint balance, uint exchange,uint numPlayers,uint time, address target) { return (hptSupply, address(this).balance,balances[msg.sender], getExchange(), hodlers.length, burnTime, burnTarget); } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { return false; if(isContract(_to)) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); return true; } else { return transferToAddress(_to, _value, _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 success) { return false; if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // 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 success) { return false; //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } }
reindex the moved hodler
hodlIndex[hodlers[index]]=index;
1,013,565
[ 1, 266, 1615, 326, 10456, 366, 369, 749, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 366, 369, 80, 1016, 63, 76, 369, 3135, 63, 1615, 13563, 33, 1615, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; library SafeMath { 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; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a / _b; } 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 c) { c = _a + _b; assert(c >= _a); return c; } } contract BaseLBSCSale { using SafeMath for uint256; address public owner; bool public paused = false; // The beneficiary is the future recipient of the funds address public beneficiary; // The crowdsale has a funding goal, cap, deadline, and minimum contribution uint public fundingGoal; uint public fundingCap; uint public minContribution; uint public decimals; bool public fundingGoalReached = false; bool public fundingCapReached = false; bool public saleClosed = false; // Time period of sale (UNIX timestamps) uint public startTime; uint public endTime; // Keeps track of the amount of wei raised uint public amountRaised; // Refund amount, should it be required uint public refundAmount; // The ratio of CHP to Ether uint public rate = 220; // prevent certain functions from being recursively called bool private rentrancy_lock = false; // A map that tracks the amount of wei contributed by address mapping(address => uint256) public balanceOf; address public manager; // Events event GoalReached(address _beneficiary, uint _amountRaised); event CapReached(address _beneficiary, uint _amountRaised); event FundTransfer(address _backer, uint _amount, bool _isContribution); event Pause(); event Unpause(); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // Modifiers modifier onlyOwner() { require(msg.sender == owner,"Only the owner is allowed to call this."); _; } modifier onlyOwnerOrManager{ require(msg.sender == owner || msg.sender == manager, "Only owner or manager is allowed to call this"); _; } modifier beforeDeadline(){ require (currentTime() < endTime, "Validation: Before endtime"); _; } modifier afterDeadline(){ require (currentTime() >= endTime, "Validation: After endtime"); _; } modifier afterStartTime(){ require (currentTime() >= startTime, "Validation: After starttime"); _; } modifier saleNotClosed(){ require (!saleClosed, "Sale is not yet ended"); _; } modifier nonReentrant() { require(!rentrancy_lock, "Validation: Reentrancy"); rentrancy_lock = true; _; rentrancy_lock = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "You are not allowed to access this time."); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "You are not allowed to access this time."); _; } constructor() public{ owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0), "Owner cannot be 0 address."); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwnerOrManager whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwnerOrManager whenPaused { paused = false; emit Unpause(); } /** * Returns the current time. * Useful to abstract calls to "now" for tests. */ function currentTime() public view returns (uint _currentTime) { return block.timestamp; } /** * The owner can terminate the crowdsale at any time. */ function terminate() external onlyOwnerOrManager { saleClosed = true; } /** * The owner can update the rate (CHP to ETH). * * @param _rate the new rate for converting CHP to ETH */ function setRate(uint _rate) public onlyOwnerOrManager { //require(_rate >= LOW_RANGE_RATE && _rate <= HIGH_RANGE_RATE); rate = _rate; } /** * The owner can unlock the fund with this function. The use- * case for this is when the owner decides after the deadline * to allow contributors to be refunded their contributions. * Note that the fund would be automatically unlocked if the * minimum funding goal were not reached. */ function ownerUnlockFund() external afterDeadline onlyOwner { fundingGoalReached = false; } /** * Checks if the funding goal has been reached. If it has, then * the GoalReached event is triggered. */ function checkFundingGoal() internal { if (!fundingGoalReached) { if (amountRaised >= fundingGoal) { fundingGoalReached = true; emit GoalReached(beneficiary, amountRaised); } } } /** * Checks if the funding cap has been reached. If it has, then * the CapReached event is triggered. */ function checkFundingCap() internal { if (!fundingCapReached) { if (amountRaised >= fundingCap) { fundingCapReached = true; saleClosed = true; emit CapReached(beneficiary, amountRaised); } } } /** * These helper functions are exposed for changing the start and end time dynamically */ function changeStartTime(uint256 _startTime) external onlyOwnerOrManager {startTime = _startTime;} function changeEndTime(uint256 _endTime) external onlyOwnerOrManager {endTime = _endTime;} function changeMinContribution(uint256 _newValue) external onlyOwnerOrManager {minContribution = _newValue * (10 ** decimals);} } contract BaseLBSCToken { using SafeMath for uint256; // Globals address public owner; mapping(address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 internal totalSupply_; // Events event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Burn(address indexed burner, uint256 value); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event Mint(address indexed to, uint256 amount); // Modifiers modifier onlyOwner() { require(msg.sender == owner,"Only the owner is allowed to call this."); _; } constructor() public{ owner = msg.sender; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender], "You do not have sufficient balance."); require(_to != address(0), "You cannot send tokens to 0 address"); 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]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ require(_value <= balances[_from], "You do not have sufficient balance."); require(_value <= allowed[_from][msg.sender], "You do not have allowance."); require(_to != address(0), "You cannot send tokens to 0 address"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256){ return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool){ allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool){ uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who], "Insufficient balance of tokens"); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender], "Insufficient allowance to burn tokens."); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0), "Owner cannot be 0 address."); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract LBSCToken is BaseLBSCToken { // Constants string public constant name = "LabelsCoin"; string public constant symbol = "LBSC"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 30000000 * (10 ** uint256(decimals)); //uint256 public constant CROWDSALE_ALLOWANCE = 1000000000 * (10 ** uint256(decimals)); uint256 public constant ADMIN_ALLOWANCE = 30000000 * (10 ** uint256(decimals)); // Properties //uint256 public totalSupply; //uint256 public crowdSaleAllowance; // the number of tokens available for crowdsales uint256 public adminAllowance; // the number of tokens available for the administrator //address public crowdSaleAddr; // the address of a crowdsale currently selling this token address public adminAddr; // the address of a crowdsale currently selling this token //bool public transferEnabled = false; // indicates if transferring tokens is enabled or not bool public transferEnabled = true; // Enables everyone to transfer tokens /** * The listed addresses are not valid recipients of tokens. * * 0x0 - the zero address is not valid * this - the contract itself should not receive tokens * owner - the owner has all the initial tokens, but cannot receive any back * adminAddr - the admin has an allowance of tokens to transfer, but does not receive any * crowdSaleAddr - the crowdsale has an allowance of tokens to transfer, but does not receive any */ modifier validDestination(address _to) { require(_to != address(0x0), "Cannot send to 0 address"); require(_to != address(this), "Cannot send to contract address"); //require(_to != owner, "Cannot send to the owner"); //require(_to != address(adminAddr), "Cannot send to admin address"); //require(_to != address(crowdSaleAddr), "Cannot send to crowdsale address"); _; } constructor(address _admin) public { require(msg.sender != _admin, "Owner and admin cannot be the same"); totalSupply_ = INITIAL_SUPPLY; adminAllowance = ADMIN_ALLOWANCE; // mint all tokens //balances[msg.sender] = totalSupply_.sub(adminAllowance); //emit Transfer(address(0x0), msg.sender, totalSupply_.sub(adminAllowance)); balances[_admin] = adminAllowance; emit Transfer(address(0x0), _admin, adminAllowance); adminAddr = _admin; approve(adminAddr, adminAllowance); } /** * Overrides ERC20 transfer function with modifier that prevents the * ability to transfer tokens until after transfers have been enabled. */ function transfer(address _to, uint256 _value) public validDestination(_to) returns (bool) { return super.transfer(_to, _value); } /** * Overrides ERC20 transferFrom function with modifier that prevents the * ability to transfer tokens until after transfers have been enabled. */ function transferFrom(address _from, address _to, uint256 _value) public validDestination(_to) returns (bool) { bool result = super.transferFrom(_from, _to, _value); if (result) { if (msg.sender == adminAddr) adminAllowance = adminAllowance.sub(_value); } return result; } } contract LBSCSale is BaseLBSCSale { using SafeMath for uint256; // The token being sold LBSCToken public tokenReward; mapping(address => bool) public approvedUsers; /** * Constructor for a crowdsale of CHPToken tokens. * * @param ifSuccessfulSendTo the beneficiary of the fund * @param fundingGoalInEthers the minimum goal to be reached * @param fundingCapInEthers the cap (maximum) size of the fund * @param minimumContribution Minimum contribution to participate in the crowdsale * @param start the start time (UNIX timestamp) * @param end the end time (UNIX timestamp) * @param rateLBSCToEther the conversion rate from LBSC to Ether * @param addressOfTokenUsedAsReward address of the token being sold * @param _manager Address that will manage the crowdsale */ constructor( address ifSuccessfulSendTo, uint fundingGoalInEthers, uint fundingCapInEthers, uint minimumContribution, uint start, uint end, uint rateLBSCToEther, address addressOfTokenUsedAsReward, address _manager ) public { require(ifSuccessfulSendTo != address(0) && ifSuccessfulSendTo != address(this), "Beneficiary cannot be 0 address"); require(addressOfTokenUsedAsReward != address(0) && addressOfTokenUsedAsReward != address(this), "Token address cannot be 0 address"); require(fundingGoalInEthers <= fundingCapInEthers, "Funding goal should be less that funding cap."); require(end > 0, "Endtime cannot be 0"); beneficiary = ifSuccessfulSendTo; fundingGoal = fundingGoalInEthers; fundingCap = fundingCapInEthers; minContribution = minimumContribution; startTime = start; endTime = end; // TODO double check rate = rateLBSCToEther; tokenReward = LBSCToken(addressOfTokenUsedAsReward); manager = _manager; decimals = tokenReward.decimals(); } /** * This fallback function is called whenever Ether is sent to the * smart contract. It can only be executed when the crowdsale is * not paused, not closed, and before the deadline has been reached. * * This function will update state variables for whether or not the * funding goal or cap have been reached. It also ensures that the * tokens are transferred to the sender, and that the correct * number of tokens are sent according to the current rate. */ function () public payable whenNotPaused beforeDeadline afterStartTime saleNotClosed nonReentrant { require(msg.value >= minContribution, "Value should be greater than minimum contribution"); require(isApprovedUser(msg.sender), "Only the approved users are allowed to participate in ICO"); // Update the sender's balance of wei contributed and the amount raised uint amount = msg.value; uint currentBalance = balanceOf[msg.sender]; balanceOf[msg.sender] = currentBalance.add(amount); amountRaised = amountRaised.add(amount); // Compute the number of tokens to be rewarded to the sender // Note: it's important for this calculation that both wei // and CHP have the same number of decimal places (18) uint numTokens = amount.mul(rate); // Transfer the tokens from the crowdsale supply to the sender if (tokenReward.transferFrom(tokenReward.owner(), msg.sender, numTokens)) { emit FundTransfer(msg.sender, amount, true); //contributions[msg.sender] = contributions[msg.sender].add(amount); // Following code is to automatically transfer ETH to beneficiary //uint balanceToSend = this.balance; //beneficiary.transfer(balanceToSend); //FundTransfer(beneficiary, balanceToSend, false); // Check if the funding goal or cap have been reached // TODO check impact on gas cost checkFundingGoal(); checkFundingCap(); } else { revert("Transaction Failed. Please try again later."); } } /** * The owner can allocate the specified amount of tokens from the * crowdsale allowance to the recipient (_to). * * NOTE: be extremely careful to get the amounts correct, which * are in units of wei and mini-LBSC. Every digit counts. * * @param _to the recipient of the tokens * @param amountInEth the amount contributed in wei * @param amountLBSC the amount of tokens transferred in mini-LBSC (18 decimals) */ function ownerAllocateTokens(address _to, uint amountInEth, uint amountLBSC) public onlyOwnerOrManager nonReentrant { if (!tokenReward.transferFrom(tokenReward.owner(), _to, convertToMini(amountLBSC))) { revert("Transfer failed. Please check allowance"); } uint amountWei = convertToMini(amountInEth); balanceOf[_to] = balanceOf[_to].add(amountWei); amountRaised = amountRaised.add(amountWei); emit FundTransfer(_to, amountWei, true); checkFundingGoal(); checkFundingCap(); } /** * The owner can call this function to withdraw the funds that * have been sent to this contract for the crowdsale subject to * the funding goal having been reached. The funds will be sent * to the beneficiary specified when the crowdsale was created. */ function ownerSafeWithdrawal() public onlyOwner nonReentrant { require(fundingGoalReached, "Check funding goal"); uint balanceToSend = address(this).balance; beneficiary.transfer(balanceToSend); emit FundTransfer(beneficiary, balanceToSend, false); } /** * This function permits anybody to withdraw the funds they have * contributed if and only if the deadline has passed and the * funding goal was not reached. */ function safeWithdrawal() public afterDeadline nonReentrant { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit FundTransfer(msg.sender, amount, false); refundAmount = refundAmount.add(amount); } } } function convertToMini(uint amount) internal view returns (uint) { return amount * (10 ** decimals); } function approveUser(address _address) external onlyOwnerOrManager { approvedUsers[_address] = true; } function disapproveUser(address _address) external onlyOwnerOrManager { approvedUsers[_address] = false; } function changeManager(address _manager) external onlyOwnerOrManager { manager = _manager; } function isApprovedUser(address _address) internal view returns (bool) { return approvedUsers[_address]; } function changeTokenAddress(address _address) external onlyOwnerOrManager { tokenReward = LBSCToken(_address); } }
* The owner can terminate the crowdsale at any time./
function terminate() external onlyOwnerOrManager { saleClosed = true; }
12,870,419
[ 1, 1986, 3410, 848, 10850, 326, 276, 492, 2377, 5349, 622, 1281, 813, 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 ]
[ 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, 10850, 1435, 3903, 1338, 5541, 1162, 1318, 288, 203, 3639, 272, 5349, 7395, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x5bd084845f8Ce18384d361BF8F4742EAd18eeD3d/sources/contracts/common/linkedlists/LinkedList.sol
* @notice Removes an element from the doubly linked list. @param list A storage pointer to the underlying list. @param key The key of the element to remove./
function remove(List storage list, bytes32 key) internal { Element storage element = list.elements[key]; require(key != bytes32(0) && contains(list, key), "key not in list"); if (element.previousKey != bytes32(0)) { Element storage previousElement = list.elements[element.previousKey]; previousElement.nextKey = element.nextKey; list.tail = element.nextKey; } if (element.nextKey != bytes32(0)) { Element storage nextElement = list.elements[element.nextKey]; nextElement.previousKey = element.previousKey; list.head = element.previousKey; } delete list.elements[key]; list.numElements = list.numElements - 1; }
16,332,644
[ 1, 6220, 392, 930, 628, 326, 741, 440, 93, 8459, 666, 18, 225, 666, 432, 2502, 4407, 358, 326, 6808, 666, 18, 225, 498, 1021, 498, 434, 326, 930, 358, 1206, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1206, 12, 682, 2502, 666, 16, 1731, 1578, 498, 13, 2713, 288, 203, 565, 3010, 2502, 930, 273, 666, 18, 6274, 63, 856, 15533, 203, 565, 2583, 12, 856, 480, 1731, 1578, 12, 20, 13, 597, 1914, 12, 1098, 16, 498, 3631, 315, 856, 486, 316, 666, 8863, 203, 565, 309, 261, 2956, 18, 11515, 653, 480, 1731, 1578, 12, 20, 3719, 288, 203, 1377, 3010, 2502, 2416, 1046, 273, 666, 18, 6274, 63, 2956, 18, 11515, 653, 15533, 203, 1377, 2416, 1046, 18, 4285, 653, 273, 930, 18, 4285, 653, 31, 203, 1377, 666, 18, 13101, 273, 930, 18, 4285, 653, 31, 203, 565, 289, 203, 203, 565, 309, 261, 2956, 18, 4285, 653, 480, 1731, 1578, 12, 20, 3719, 288, 203, 1377, 3010, 2502, 14512, 273, 666, 18, 6274, 63, 2956, 18, 4285, 653, 15533, 203, 1377, 14512, 18, 11515, 653, 273, 930, 18, 11515, 653, 31, 203, 1377, 666, 18, 1978, 273, 930, 18, 11515, 653, 31, 203, 565, 289, 203, 203, 565, 1430, 666, 18, 6274, 63, 856, 15533, 203, 565, 666, 18, 2107, 3471, 273, 666, 18, 2107, 3471, 300, 404, 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 ]
./full_match/137/0x919418623045861F29033EF11ccD66E0bca2F880/sources/project_/contracts/libraries/PoolTradeHelpers.sol
* @dev Quantity in pips of asset that order wallet is receiving from pool/
function calculateOrderCreditQuantityInPips( PoolTrade memory self, OrderSide orderSide ) internal pure returns (uint64) { return ( orderSide == OrderSide.Buy ? self.netBaseQuantityInPips : self.netQuoteQuantityInPips ) - self.takerGasFeeQuantityInPips; }
3,745,929
[ 1, 12035, 316, 293, 7146, 434, 3310, 716, 1353, 9230, 353, 15847, 628, 2845, 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, 225, 445, 4604, 2448, 16520, 12035, 382, 52, 7146, 12, 203, 565, 8828, 22583, 3778, 365, 16, 203, 565, 4347, 8895, 1353, 8895, 203, 225, 262, 2713, 16618, 1135, 261, 11890, 1105, 13, 288, 203, 565, 327, 203, 1377, 261, 203, 3639, 1353, 8895, 422, 4347, 8895, 18, 38, 9835, 203, 1850, 692, 365, 18, 2758, 2171, 12035, 382, 52, 7146, 203, 1850, 294, 365, 18, 2758, 10257, 12035, 382, 52, 7146, 203, 1377, 262, 300, 365, 18, 88, 6388, 27998, 14667, 12035, 382, 52, 7146, 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 ]
./full_match/56/0x7e9948A7d80c5f8e5d78291b74e9DFeAc7f08955/sources/contracts/prod_usd_/ICO_IndexxUSDP.sol
* @dev Function to buy Indexx token through any BEP20 token @param _beneficiary Address of investor @param _amount Amount of coin paid by investor @param tokenAddress Address of BEP20 token used/ calculate token amount to be created
function buyIndexxFromAnyBEP20( address _beneficiary, uint256 _amount, address tokenAddress ) external onlyWhileOpen { uint256 weiAmount = _amount; _preValidateTokenPurchase(_beneficiary, tokenAddress); _transferPayment(_beneficiary, weiAmount, tokenAddress); uint256 tokens = _getTokenAmount(weiAmount, tokenAddress); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, tokenAddress, weiAmount, tokens); _updatePurchasingState(_beneficiary, tokens); _postValidatePurchase(_beneficiary, tokens); }
3,238,112
[ 1, 2083, 358, 30143, 3340, 92, 1147, 3059, 1281, 9722, 52, 3462, 1147, 225, 389, 70, 4009, 74, 14463, 814, 5267, 434, 2198, 395, 280, 225, 389, 8949, 16811, 434, 13170, 30591, 635, 2198, 395, 280, 225, 1147, 1887, 5267, 434, 9722, 52, 3462, 1147, 1399, 19, 4604, 1147, 3844, 358, 506, 2522, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1016, 92, 1265, 2961, 5948, 52, 3462, 12, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1758, 1147, 1887, 203, 565, 262, 3903, 1338, 15151, 3678, 288, 203, 3639, 2254, 5034, 732, 77, 6275, 273, 389, 8949, 31, 203, 3639, 389, 1484, 4270, 1345, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 1147, 1887, 1769, 203, 3639, 389, 13866, 6032, 24899, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 16, 1147, 1887, 1769, 203, 3639, 2254, 5034, 2430, 273, 389, 588, 1345, 6275, 12, 1814, 77, 6275, 16, 1147, 1887, 1769, 203, 203, 3639, 389, 2567, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 2430, 1769, 203, 3639, 3626, 3155, 23164, 12, 3576, 18, 15330, 16, 1147, 1887, 16, 732, 77, 6275, 16, 2430, 1769, 203, 203, 3639, 389, 2725, 10262, 343, 11730, 1119, 24899, 70, 4009, 74, 14463, 814, 16, 2430, 1769, 203, 3639, 389, 2767, 4270, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 2430, 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 ]
./full_match/1/0x3c1164531d5857029ae5412E49999306547834d8/sources/contracts/implementations/abstract/RMRKAbstractEquippableMP.sol
* @inheritdoc IERC165/
function supportsInterface( bytes4 interfaceId ) public view virtual override(IERC165, RMRKMinifiedEquippable) returns (bool) { return super.supportsInterface(interfaceId) || interfaceId == type(IERC2981).interfaceId || interfaceId == RMRK_INTERFACE; }
9,657,861
[ 1, 36, 10093, 467, 654, 39, 28275, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6146, 1358, 12, 203, 3639, 1731, 24, 1560, 548, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 12, 45, 654, 39, 28275, 16, 534, 23464, 47, 2930, 939, 13142, 15491, 429, 13, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 203, 5411, 2240, 18, 28064, 1358, 12, 5831, 548, 13, 747, 203, 5411, 1560, 548, 422, 618, 12, 45, 654, 39, 5540, 11861, 2934, 5831, 548, 747, 203, 5411, 1560, 548, 422, 534, 23464, 47, 67, 18865, 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 ]
./full_match/5/0x8a44aF939D25C17f55088ea06bFCD43A80dB4f85/sources/src/base/MSSCBase.sol
Retrieve the total number of instructions and place on the stack. Ignore claimed instructions, this comes handy when dealing with hybrid Settlement Cycles. Skip overflow check as for loop is indexed starting at zero.
function _execute(bytes32 cycleId) internal { if (_cycles[cycleId].executed) revert CycleAlreadyExecuted(); _cycles[cycleId].executed = true; bytes32[] memory instructions = _cycles[cycleId].instructions; uint256 totalInstructions = instructions.length; for (uint256 i = 0; i < totalInstructions; ) { InstructionManagerLib.Instruction storage instruction = _instructions[instructions[i]]; if ( instruction.depositStatus != InstructionManagerLib.DepositStatus.CLAIMED ) { instruction.claim(); } unchecked { ++i; } } }
7,090,396
[ 1, 5767, 326, 2078, 1300, 434, 12509, 471, 3166, 603, 326, 2110, 18, 8049, 7516, 329, 12509, 16, 333, 14535, 948, 93, 1347, 21964, 598, 30190, 1000, 88, 806, 22337, 9558, 18, 6611, 9391, 866, 487, 364, 2798, 353, 8808, 5023, 622, 3634, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 8837, 12, 3890, 1578, 8589, 548, 13, 2713, 288, 203, 3639, 309, 261, 67, 23976, 63, 13946, 548, 8009, 4177, 4817, 13, 15226, 385, 3409, 9430, 23839, 5621, 203, 203, 3639, 389, 23976, 63, 13946, 548, 8009, 4177, 4817, 273, 638, 31, 203, 3639, 1731, 1578, 8526, 3778, 12509, 273, 389, 23976, 63, 13946, 548, 8009, 25758, 31, 203, 203, 3639, 2254, 5034, 2078, 26712, 273, 12509, 18, 2469, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2078, 26712, 31, 262, 288, 203, 5411, 24605, 1318, 5664, 18, 11983, 203, 7734, 2502, 7592, 273, 389, 25758, 63, 25758, 63, 77, 13563, 31, 203, 203, 5411, 309, 261, 203, 7734, 7592, 18, 323, 1724, 1482, 480, 203, 7734, 24605, 1318, 5664, 18, 758, 1724, 1482, 18, 15961, 3114, 40, 203, 5411, 262, 288, 203, 7734, 7592, 18, 14784, 5621, 203, 5411, 289, 203, 203, 5411, 22893, 288, 203, 7734, 965, 77, 31, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNDOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN8OOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN8OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOODNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO8NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO8NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOODNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNMOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNMOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNDOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOODNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO7=~~~~~~+$OOOOOOOOOOOOOOOOOOOOOOO8NNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO?~~~~~~~~~~~~~~~~~~~~~~+OOOOOOOOOOOOOOOOOOO8NNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOO==~~~~~~~~~~~~~~~~~~~~~~~~~~~~=$OOOOOOOOOOOOOOOOMNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOI~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~8OOOOOOOOOOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~OOOOOOOOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOI=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~OOOOOOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOZ=~~~~~~~~~~~~~~~+NMMMMMO?~~~~~~~~~~~~~~~~~~~~~~~~~~~ZOOOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=~NN==~~~~~~~~~~~~~~~~~~~~$ZOOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOO7~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~OOOONNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNDOOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~OODNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNMMMMMMM8OOOOOOOO=~~~~~~~~~~~~~~~~~~~~~~ONMMMMMMMMMMMMM?==~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNMMMMMMMMMMMMMDZ~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMM==~~~~~~~~~~M=~==DMMMMMNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNOOOODMMMMMMMMMMMMMMMMMI~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~~~~7MMMMMMMMMMMNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNOOOOOOOOOOONMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN~~~~NNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNDOOOOOOOOOOOOOO===~IMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM8~=~~~~~~~~~NNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNOOOOOOOOOOOOOOO~~~~~~~~~~==~~=$MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM?~~~~~~~~~~~~~~~~~~=~NNNNNNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~~~~~~~~~~~~~~~~~~~~?NNNNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOOO$=~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM8~~~~~~~~~~~~~~~~~~~~~~~~+NNNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOOI~~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNN NNNNNNNNNNNNNNNOOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM=~~~:...........=8MM+=~~~~~~NNNNNNNNNN NNNNNNNNNNNNNNNNOOOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~=MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM~~~~.....MM?............DN~~MNNNNNNNNN NNNNNNNNNNNNNNNNOOOOOOOOOOO+~~~~~~~~~~~~~~~~~~~~~~~MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM=~~~~........................MNNNNNNNNN NNNNNNNNNNNNNNNNNOOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~?MMMMMMMMMMMMMMMMMMMMMMMMMMMMD~~~~~........................NNNNNNNNNN NNNNNNNNNNNNNNNNNDOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~DMMMMMMMMMMMMMMMMMMMMMMMMMMZ~~~~~~........................NNNNNNNNNN NNNNNNNNNNNNNNNNNNOOOOOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~=IMMMMMMMMMMMMMMMMMMMMMMMMO~~~~~~~.......................~NNNNNNNNNN NNNNNNNNNNNNNNNNNNOOOOOOOO7~~~~~~~~~~~~~~~~~~~~~~~~~~~=MMMMMMMMMMMMMMMMMMMMMM~~~~~~~~~=......................NNNNNNNNNNN NNNNNNNNNNNNNNNNNNOOOOOO$~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ZMMMMMMMMMMMMMMMMMM~~~~~~~~~~~~,....................NNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNOOOOO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NMMMMMMMMMMMMMM=~~~~~~~~~~~~~~,..................NNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNOOO+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~8MMMMMMMI~~~~~~~~~~~~~~~~M~~~,..............MNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNMOO=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~N~~~~~~........~~~NNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNN8~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~M~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$~~~~~~~M~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MI~~~N~~~~~~~~~~~~~~~~MNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNZ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNDO~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNZ=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=~~~~~~~~~~~~~~~~~~=~NNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=+DM8~~~~~~~$MN~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNZ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNZ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~8NNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=MNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN7~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~DNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNND~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN$~~~~~~~~~~~~~~~~==~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN:~~~~~~~~~~~~~~~~~~~~~~~~~=~~~~~~~~~~~~~=~~~~~NNNNNNNNNNNNNNNNNNNNWE&ARE&LEGIONNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNWE&DO&NOT&FORGIVENNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN8~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNWE&DO&NOT&FORGETNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNEXPECT&USNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNM~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~=NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN=~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN */ /** * @title Microverse * Given the fact that most of the blockchaaaaains are dogshit wrapped in catshit, we've decided to come down from the * highland, just for a while, though. * Being smart is lonely, being nice is a compromise. * Hello human, we are Evil Morty Fund. * Decentralization is great, while balance must be kept. * Order will change, but never disappear. * We are not building another chain, we are forming a soceity, never seen, never have been. */ // \ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) / // \ (•◡•) / █ █ █░░█ █▀▀▄ █▀▀█ █░░ █░░█ █▀▀▄ █▀▀█ █▀▀▄ █░░█ █▀▀▄ █▀▀▄ █░░█ █▀▀▄ \ (•◡•) / // \ (•◡•) / █ █ █ █░░█ █▀▀▄ █▄▄█ █░░ █░░█ █▀▀▄ █▄▄█ █░░█ █░░█ █▀▀▄ █░░█ █░░█ █▀▀▄ \ (•◡•) / // \ (•◡•) / █▄▀▄█ ░▀▀▀ ▀▀▀░ ▀░░▀ ▀▀▀ ░▀▀▀ ▀▀▀░ ▀░░▀ ▀▀▀░ ░▀▀▀ ▀▀▀░ ▀▀▀░ ░▀▀▀ ▀▀▀░ \ (•◡•) / // \ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) /\ (•◡•) / /** * Created on 2018-08-21 03:28 * @summary: * @author: yong */ pragma solidity ^0.4.23; /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * @dev Supports unlimited numbers of roles and addresses. * @dev See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Superuser * @dev The Superuser contract defines a single superuser who can transfer the ownership * @dev of a contract to a new address, even if he is not the owner. * @dev A superuser can transfer his role to a new address. */ contract Superuser is Ownable, RBAC { string public constant ROLE_SUPERUSER = "superuser"; constructor () public { addRole(msg.sender, ROLE_SUPERUSER); } /** * @dev Throws if called by any account that's not a superuser. */ modifier onlySuperuser() { checkRole(msg.sender, ROLE_SUPERUSER); _; } modifier onlyOwnerOrSuperuser() { require(msg.sender == owner || isSuperuser(msg.sender)); _; } /** * @dev getter to determine if address has superuser role */ function isSuperuser(address _addr) public view returns (bool) { return hasRole(_addr, ROLE_SUPERUSER); } /** * @dev Allows the current superuser to transfer his role to a newSuperuser. * @param _newSuperuser The address to transfer ownership to. */ function transferSuperuser(address _newSuperuser) public onlyOwner { require(_newSuperuser != address(0)); removeRole(msg.sender, ROLE_SUPERUSER); addRole(_newSuperuser, ROLE_SUPERUSER); } } /** * @title MicroverseBase * @dev You are still with us? im almost surprised. * @dev Basic params are defined in this base. */ contract MicroverseBase is Superuser { using SafeMath for uint256; event OpenWormhole(); event CloseWormhole(); event SystemChangePercentWeiDividend(uint256 oldValue, uint256 newValue); event SystemChangePercentWeiJackpot(uint256 oldValue, uint256 newValue); event SystemChangePercentWeiMC(uint256 oldValue, uint256 newValue); uint256 public previousWeiBalance; uint256 public nextSeedHashed; uint256 public percentWeiDividend = 40; // 40% uint256 public percentWeiJackpot = 10; // 10% uint256 public percentWeiMC = 10; // 10% uint256 public FACTOR = 100; // We think it makes perfectly sense that only the owner can open or close the wormhole. bool public wormholeIsOpen = true; modifier wormholeOpened() { require (wormholeIsOpen == true); _; } /** * @dev start game */ function openWormhole() external onlyOwner { wormholeIsOpen = true; emit OpenWormhole(); } /** * @dev stop game */ function closeWormhole() external onlyOwner { wormholeIsOpen = false; emit CloseWormhole(); } /** * @dev reveal the hashed seed to general public * @dev the seed will be hashed twice using keccak256 * @param seedHash The result of keccak256(keccak256(seed)) */ function setNextSeedHash(uint256 seedHash) external onlyOwner { nextSeedHashed = seedHash; } /** * @dev Update dividend percentage, a system event * is sent to capture this change. * @param _value new value */ function setPercentWeiDividend(uint256 _value) external onlyOwner { emit SystemChangePercentWeiDividend(percentWeiDividend, _value); percentWeiDividend = _value; } /** * @dev Update jackpot percentage, a system event * is sent to capture this change. * @param _value new value */ function setPercentWeiJackpot(uint256 _value) external onlyOwner { emit SystemChangePercentWeiJackpot(percentWeiJackpot, _value); percentWeiJackpot = _value; } /** * @dev Update mutual constructor percentage, a system event * is sent to capture this change. * @param _value new value */ function setPercentWeiMC(uint256 _value) external onlyOwner { emit SystemChangePercentWeiMC(percentWeiMC, _value); percentWeiMC = _value; } } /** * Microverse is made up of four components, together managing three ERC223 tokens. * Let us explain. * * ░█▀▀█ █▀▀█ █▀▀█ █▀▀█ █▀▀▀ █▀▀ * ░█─▄▄ █▄▄█ █▄▄▀ █▄▄█ █─▀█ █▀▀ * ░█▄▄█ ▀──▀ ▀─▀▀ ▀──▀ ▀▀▀▀ ▀▀▀ * * Garage manages Evil Morty token (Morty) * It tracks and updates the price, manage the total balance, and timestamp in this universe. * * ░█▀▀█ █▀▀█ █▀▀█ ▀▀█▀▀ █▀▀█ █──   ░█▀▀█ █──█ █▀▀▄ * ░█▄▄█ █──█ █▄▄▀ ──█── █▄▄█ █──   ░█─▄▄ █──█ █──█ * ░█─── ▀▀▀▀ ▀─▀▀ ──▀── ▀──▀ ▀▀▀   ░█▄▄█ ─▀▀▀ ▀──▀ * * Portal Gun manages Evil Morty token (Morty), Rick C137 token (Rick), and Flurbo token (FLB) * It takes care of the random process happened in this universe, in which the sender gets * 20% chance to get Rick, 30% chance to get double Morty, and 50% chance to get FLB, if, * he/she sends EM to the address of this contract. * * ▒█▀▀▀█ █▀▀█ █▀▀█ █▀▀ █▀▀   ▒█▀▀█ █▀▀█ █░░█ ░▀░ █▀▀ █▀▀ * ░▀▀▀▄▄ █░░█ █▄▄█ █░░ █▀▀   ▒█░░░ █▄▄▀ █░░█ ▀█▀ ▀▀█ █▀▀ * ▒█▄▄▄█ █▀▀▀ ▀░░▀ ▀▀▀ ▀▀▀   ▒█▄▄█ ▀░▀▀ ░▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀ * * Spaceship manages Rick C137 tokens (Rick) * It is responsible for sending the dividends. * * ▒█▀▀█ ░▀░ █▀▀█ █▀▀▄ █▀▄▀█ █▀▀█ █▀▀▄ * ▒█▀▀▄ ▀█▀ █▄▄▀ █░░█ █░▀░█ █▄▄█ █░░█ * ▒█▄▄█ ▀▀▀ ▀░▀▀ ▀▀▀░ ▀░░░▀ ▀░░▀ ▀░░▀ * * Birdman helps grow the Microverse community. * This contract sends the fund to birdmen. * */ /** * @title GarageInterface * @dev Housekeeper for Evil Morty token. */ contract GarageInterface { /** * @dev getter for token address */ function getEvilMortyAddress() external view returns (address); /** * @dev proxy/agent to purchase morties on behalf of senders * @param weiAmount The ether amount * @param beneficiary The buyer's address */ function citadelBuy(uint256 weiAmount, address beneficiary) external returns (uint256); } /** * @title PortalGunInterface * @dev Random oracle in this world. */ contract PortalGunInterFace { uint256 public numTickets; /** * @dev Give us morty, let there be rick * @param player The player's address * @param amount Amount morty sent */ function participate(address player, uint256 amount) external; /** * @dev getter to check EM balance * @param sender The sender's address */ function balanceOfMorty(address sender) external view returns (uint256); /** * @dev getter to check C137 balance * @param sender The sender's address */ function balanceOfRick(address sender) external view returns (uint256); /** * @dev getter to check FLB balance * @param sender The sender's address */ function balanceOfFlurbo(address sender) external view returns (uint256); /** * @dev Give back EM, C137, or FLB * @param seed A UUID in expressed in integer */ function redeem(uint256 seed) external; /** * @dev Wake Rick up */ function startRick() external returns (bool); /** * @dev Clean all ricks * @dev Remember, for a given period of time, Rick C137 holders are eligible for receiving ETH dividends. * @dev When the period ends, all ricks will be gone, C137 balance will be reset to zero. * @dev Our strategy is, get ricks as early as possible! */ function resetRick() external; /** * @dev Make portal gun back on fire */ function startPortalGun() external; /** * @dev Cease fire and make Rick drunk */ function stopPortalGunAndRick() external; /** * @dev getter of number of C137 holders */ function getNumOfRickHolders() external view returns (uint256); } /** * @title SpaceshipInterface */ contract SpaceshipInterface { /** * @dev What more can i say @jeff? It starts the spaceship */ function startSpaceship() external returns (bool); /** * @dev Send the eth funds to all C137 holders */ function sendDividends() external; /** * @dev getter of number of dividend rounds */ function getNumDividends() external view returns (uint256); /** * @dev updates the status, that's it */ function updateSpaceshipStatus() external; } /** * ╔═╗╔═╦══╦═══╦═══╦═══╦╗░░╔╦═══╦═══╦═══╦═══╗ * ║║╚╝║╠╣╠╣╔═╗║╔═╗║╔═╗║╚╗╔╝║╔══╣╔═╗║╔═╗║╔══╝ * ║╔╗╔╗║║║║║░╚╣╚═╝║║░║╠╗║║╔╣╚══╣╚═╝║╚══╣╚══╗ * ║║║║║║║║║║░╔╣╔╗╔╣║░║║║╚╝║║╔══╣╔╗╔╩══╗║╔══╝ * ║║║║║╠╣╠╣╚═╝║║║╚╣╚═╝║╚╗╔╝║╚══╣║║╚╣╚═╝║╚══╗ * ╚╝╚╝╚╩══╩═══╩╝╚═╩═══╝░╚╝░╚═══╩╝╚═╩═══╩═══╝ * * It's been a great pleasure coding in solidity! * * @title Microverse * @dev secret: 981ea44275dc95cb74b8f768f82d6debfd2f934adc0125de71762051 * * ██████┼────────────────────────────────────────────────────────────┼██████ * ██████│░░░Ryan░░░░░░░░░░░░░░░░░░░░░░░░░Dan░░░░░░░░░░░░░░░░Justin░░░│██████ * ██████│░Einstein░░░░░░░░░░░░░Satoshi░░░░░░░░░░░░░░░░░Stephen░░░░░░░│██████ * ██████│░░░░░░░░░Shannon░░░░░░░░░░░░░░░░░RSA░░░░░░░░░░░░░░░░░░░░░░░░│██████ * ██████│░░░░░░░░░░░Vitalik░░░░░░░░░░░░░░░░░░░░░All Team Members░░░░░│██████ * ██████│░░░░░░Steve░░░░░░░░░░Mandela░░░░░░░░░░Lennon░░░░░░░░░░░░░░░░│██████ * ██████│░░░░░░░░░░░░░░░░Gabriel░░░░░░░░░Haruki░░░░░░░░░░░░░THANKS░TO│██████ * ██████┼────────────────────────────────────────────────────────────┼██████ * ██████████████████████████████████████████████████████████████████████████ * █████████████████████████ https://microverse.club ████████████████████████ * ██████████████████████████████████████████████████████████████████████████ * ██████████████████████████████████████████████████████████████████████████ */ contract Microverse is MicroverseBase { event Refund(address indexed receiver, uint256 value); event Withdraw(address indexed receiver, uint256 value); GarageInterface internal garageInstance; PortalGunInterFace internal portalGunInstance; SpaceshipInterface internal spaceshipInstance; address internal EvilMortyAddress; address internal MCAddress; modifier isEvilMortyToken() { require(msg.sender == EvilMortyAddress); _; } constructor( address garageAddress, address portalGunAddress, address spaceshipAddress, address MutualConstructorAddress) public { garageInstance = GarageInterface(garageAddress); portalGunInstance = PortalGunInterFace(portalGunAddress); spaceshipInstance = SpaceshipInterface(spaceshipAddress); EvilMortyAddress = garageInstance.getEvilMortyAddress(); MCAddress = MutualConstructorAddress; } /** * @dev Enable sending eth directly */ function () public payable { if (msg.sender == owner) { return; } buyMorty(); } /** * @dev Respond to Evil Morty token transfer * @param _from address * @param _value address * @param _data extra data */ function tokenFallback(address _from, uint _value, bytes _data) public wormholeOpened isEvilMortyToken { if (_from == owner) { return; } portalGunInstance.participate(_from, _value); } /** * @dev Check morty balance of a given address * @param sender address */ function balanceOfMorty(address sender) external view returns (uint256) { return portalGunInstance.balanceOfMorty(sender); } /** * @dev Check rick balance of a given address * @param sender address */ function balanceOfRick(address sender) external view returns (uint256) { return portalGunInstance.balanceOfRick(sender); } /** * @dev Check flurbo of a given address * @param sender address */ function balanceOfFlurbo(address sender) external view returns (uint256) { return portalGunInstance.balanceOfFlurbo(sender); } /** * @dev Agent for buying morties * if the user sends more eth fund than needed, the exceedings will be sent back * i.e., if there are only 1000 morties left, each morty costs 0.001 eth, and the * user sends 3 eth, then, after the purchase (1000 * 0.001 = 1 eth), the remaining * 2 eth will be refunded. */ function buyMorty() public wormholeOpened payable { uint256 weiReturn = garageInstance.citadelBuy(msg.value, msg.sender); if (weiReturn > 0) { msg.sender.transfer(weiReturn); emit Refund(msg.sender, weiReturn); } _addWeiAmount(address(this).balance.sub(previousWeiBalance)); } /** * @dev Transfer jackpot to the winner * @param winner address */ function transferJackpot(address winner) external onlyOwner returns (bool) { uint256 weiJackpot = address(this).balance; emit Withdraw(winner, weiJackpot); winner.transfer(weiJackpot); previousWeiBalance = 0; } /** * @dev Consume tickets to generate morty, rick, or flurbo * @param seed A uuid4 in int format */ function redeemLottery(uint256 seed) external onlyOwnerOrSuperuser { return portalGunInstance.redeem(seed); } /** * @dev Get number of tickets onhold */ function getNumOfLotteryTickets() external view returns (uint256) { return portalGunInstance.numTickets(); } /** * @dev Internal function to update funds for jackpot and dividends * @param weiAmount eth amount in wei */ function _addWeiAmount(uint256 weiAmount) internal returns (bool) { uint256 weiDividendPart = weiAmount.mul(percentWeiDividend).div(FACTOR); // 40% uint256 weiJackpotPart = weiAmount.mul(percentWeiJackpot).div(FACTOR); // 10% uint256 weiMCPart = weiAmount.mul(percentWeiMC).div(FACTOR); // 10% uint256 weiEMFPart = weiAmount.sub(weiDividendPart).sub(weiJackpotPart).sub(weiMCPart); address(spaceshipInstance).transfer(weiDividendPart); MCAddress.transfer(weiMCPart); address(owner).transfer(weiEMFPart); previousWeiBalance = address(this).balance; return true; } /** * @dev Before sending dividends, there are some preparations to be made. * Spaceship needs to know the number of current Rick holders and * the number of total Ricks. Any events causing changes in balance of Ricks * need to be stopped, which means, the Portal Gun service is paused and, * transferring of Ricks are paused. */ function prepareDividends() external onlyOwnerOrSuperuser { spaceshipInstance.updateSpaceshipStatus(); portalGunInstance.stopPortalGunAndRick(); } /** * @dev Send eth to all Rick holders */ function transferDividends() external onlyOwnerOrSuperuser { return spaceshipInstance.sendDividends(); } /** * @dev Get number of Rick holders in Spaceship */ function getNumDividends() external view returns (uint256) { return spaceshipInstance.getNumDividends(); } /** * @dev Once the distribution of dividends is finished * the system will be started */ function finishDividends() external onlyOwnerOrSuperuser { spaceshipInstance.startSpaceship(); portalGunInstance.startPortalGun(); portalGunInstance.startRick(); } /** * @dev Reset all Rick holders */ function resetDividends() external onlyOwnerOrSuperuser { return portalGunInstance.resetRick(); } /** * @dev Get number of Rick holders in Portal Gun */ function getNumOfRickHolders() external view returns (uint256) { return portalGunInstance.getNumOfRickHolders(); } /** * @dev Upgrade Microverse's components * in case of upgrade needed */ function upgradeComponent( uint256 _componentIndex, address _address) external onlyOwner { uint256 codeLength; assembly { codeLength := extcodesize(_address) } if (codeLength == 0) { return; } if (_componentIndex == 1) { garageInstance = GarageInterface(_address); return; } if (_componentIndex == 2) { portalGunInstance = PortalGunInterFace(_address); return; } if (_componentIndex == 3) { spaceshipInstance = SpaceshipInterface(_address); return; } } /** * @dev refresh evil morty's address */ function upgradeEvilMorty() external onlyOwner { EvilMortyAddress = garageInstance.getEvilMortyAddress(); } } /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
* @dev Check flurbo of a given address @param sender address/
function balanceOfFlurbo(address sender) external view returns (uint256) { return portalGunInstance.balanceOfFlurbo(sender); }
14,022,860
[ 1, 1564, 1183, 295, 1075, 434, 279, 864, 1758, 225, 5793, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 2340, 295, 1075, 12, 2867, 5793, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 11899, 43, 318, 1442, 18, 12296, 951, 2340, 295, 1075, 12, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x89eE2edA0a7201014Ed800db7b526DBD17AFc176/sources/contracts/Boost.sol
Define a struct for the user's lock status
struct LockStatus { uint256 lockAmount; uint256 unlockTime; uint256 duration; uint256 miningBoost; } uint256 public constant MAX_TOTAL_LOCK_FLOOR = 10000 ether; uint256 public totalLockFloor; uint256 public totalLockAmount; esTokenLockSetting[] public esTokenLockSettings; mapping(address => LockStatus) public userLockStatus; IesToken public esToken; IesToken public token; uint256 public constant MAX_STAKING_POOLS = 10; EnumerableSetUpgradeable.AddressSet private stakingPools; event StakingPoolAdded(address indexed poolAddress); event StakingPoolRemoved(address indexed poolAddress);
4,899,365
[ 1, 11644, 279, 1958, 364, 326, 729, 1807, 2176, 1267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 3488, 1482, 288, 203, 3639, 2254, 5034, 2176, 6275, 31, 203, 3639, 2254, 5034, 7186, 950, 31, 203, 3639, 2254, 5034, 3734, 31, 203, 3639, 2254, 5034, 1131, 310, 26653, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 28624, 67, 6589, 67, 42, 1502, 916, 273, 12619, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 2078, 2531, 42, 5807, 31, 203, 565, 2254, 5034, 1071, 2078, 2531, 6275, 31, 203, 203, 565, 5001, 1345, 2531, 5568, 8526, 1071, 5001, 1345, 2531, 2628, 31, 203, 565, 2874, 12, 2867, 516, 3488, 1482, 13, 1071, 729, 2531, 1482, 31, 203, 565, 467, 281, 1345, 1071, 5001, 1345, 31, 203, 565, 467, 281, 1345, 1071, 1147, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 882, 14607, 1360, 67, 20339, 55, 273, 1728, 31, 203, 565, 6057, 25121, 694, 10784, 429, 18, 1887, 694, 3238, 384, 6159, 16639, 31, 203, 203, 565, 871, 934, 6159, 2864, 8602, 12, 2867, 8808, 2845, 1887, 1769, 203, 565, 871, 934, 6159, 2864, 10026, 12, 2867, 8808, 2845, 1887, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * The OGXNext "Orgura Exchange" token contract bases on the ERC20 standard token contracts * OGX Coin ICO. (Orgura group) * authors: Roongrote Suranart * */ pragma solidity ^0.4.20; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // 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) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) public 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 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 TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint64 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public { require(_releaseTime > uint64(block.timestamp)); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(uint64(block.timestamp) >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } /** * @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 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Owned { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Owned() public { owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } modifier onlyOwner { require(msg.sender == owner); _; } } contract OrguraExchange is StandardToken, Owned { string public constant name = "Orgura Exchange"; string public constant symbol = "OGX"; uint8 public constant decimals = 18; /// Maximum tokens to be allocated. uint256 public constant HARD_CAP = 800000000 * 10**uint256(decimals); /* Initial supply is 800,000,000 OGX */ /// Maximum tokens to be allocated on the sale (50% of the hard cap) uint256 public constant TOKENS_SALE_HARD_CAP = 400000000 * 10**uint256(decimals); /// Base exchange rate is set to 1 ETH = 7,169 OGX. uint256 public constant BASE_RATE = 7169; /// seconds since 01.01.1970 to 19.04.2018 (0:00:00 o'clock UTC) /// HOT sale start time uint64 private constant dateSeedSale = 1523145600 + 0 hours; // 8 April 2018 00:00:00 o'clock UTC /// Seed sale end time; Sale PreSale start time 20.04.2018 uint64 private constant datePreSale = 1524182400 + 0 hours; // 20 April 2018 0:00:00 o'clock UTC /// Sale PreSale end time; Sale Round 1 start time 1.05.2018 uint64 private constant dateSaleR1 = 1525132800 + 0 hours; // 1 May 2018 0:00:00 o'clock UTC /// Sale Round 1 end time; Sale Round 2 start time 15.05.2018 uint64 private constant dateSaleR2 = 1526342400 + 0 hours; // 15 May 2018 0:00:00 o'clock UTC /// Sale Round 2 end time; Sale Round 3 start time 31.05.2018 uint64 private constant dateSaleR3 = 1527724800 + 0 hours; // 31 May 2018 0:00:00 o'clock UTC /// Sale Round 3 end time; 14.06.2018 0:00:00 o'clock UTC uint64 private constant date14June2018 = 1528934400 + 0 hours; /// Token trading opening time (14.07.2018) uint64 private constant date14July2018 = 1531526400; /// token caps for each round uint256[5] private roundCaps = [ 50000000* 10**uint256(decimals), // Sale Seed 50M 50000000* 10**uint256(decimals), // Sale Presale 50M 100000000* 10**uint256(decimals), // Sale Round 1 100M 100000000* 10**uint256(decimals), // Sale Round 2 100M 100000000* 10**uint256(decimals) // Sale Round 3 100M ]; uint8[5] private roundDiscountPercentages = [90, 75, 50, 30, 15]; /// Date Locked until uint64[4] private dateTokensLockedTills = [ 1536883200, // locked until this date (14 Sep 2018) 00:00:00 o'clock UTC 1544745600, // locked until this date (14 Dec 2018) 00:00:00 o'clock UTC 1557792000, // locked until this date (14 May 2019) 00:00:00 o'clock UTC 1581638400 // locked until this date (14 Feb 2020) 00:00:00 o'clock UTC ]; //Locked Unil percentages uint8[4] private lockedTillPercentages = [20, 20, 30, 30]; /// team tokens are locked until this date (27 APR 2019) 00:00:00 uint64 private constant dateTeamTokensLockedTill = 1556323200; /// no tokens can be ever issued when this is set to "true" bool public tokenSaleClosed = false; /// contract to be called to release the Penthamon team tokens address public timelockContractAddress; modifier inProgress { require(totalSupply < TOKENS_SALE_HARD_CAP && !tokenSaleClosed && now >= dateSeedSale); _; } /// Allow the closing to happen only once modifier beforeEnd { require(!tokenSaleClosed); _; } /// Require that the token sale has been closed modifier tradingOpen { //Begin ad token sale closed //require(tokenSaleClosed); //_; //Begin at date trading open setting require(uint64(block.timestamp) > date14July2018); _; } function OrguraExchange() public { } /// @dev This default function allows token to be purchased by directly /// sending ether to this smart contract. function () public payable { purchaseTokens(msg.sender); } /// @dev Issue token based on Ether received. /// @param _beneficiary Address that newly issued token will be sent to. function purchaseTokens(address _beneficiary) public payable inProgress { // only accept a minimum amount of ETH? require(msg.value >= 0.01 ether); uint256 tokens = computeTokenAmount(msg.value); // roll back if hard cap reached require(totalSupply.add(tokens) <= TOKENS_SALE_HARD_CAP); doIssueTokens(_beneficiary, tokens); /// forward the raised funds to the contract creator owner.transfer(this.balance); } /// @dev Batch issue tokens on the presale /// @param _addresses addresses that the presale tokens will be sent to. /// @param _addresses the amounts of tokens, with decimals expanded (full). function issueTokensMulti(address[] _addresses, uint256[] _tokens) public onlyOwner beforeEnd { require(_addresses.length == _tokens.length); require(_addresses.length <= 100); for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { doIssueTokens(_addresses[i], _tokens[i]); } } /// @dev Issue tokens for a single buyer on the presale /// @param _beneficiary addresses that the presale tokens will be sent to. /// @param _tokens the amount of tokens, with decimals expanded (full). function issueTokens(address _beneficiary, uint256 _tokens) public onlyOwner beforeEnd { doIssueTokens(_beneficiary, _tokens); } /// @dev issue tokens for a single buyer /// @param _beneficiary addresses that the tokens will be sent to. /// @param _tokens the amount of tokens, with decimals expanded (full). function doIssueTokens(address _beneficiary, uint256 _tokens) internal { require(_beneficiary != address(0)); // increase token total supply totalSupply = totalSupply.add(_tokens); // update the beneficiary balance to number of tokens sent balances[_beneficiary] = balances[_beneficiary].add(_tokens); // event is fired when tokens issued Transfer(address(0), _beneficiary, _tokens); } /// @dev Returns the current price. function price() public view returns (uint256 tokens) { return computeTokenAmount(1 ether); } /// @dev Compute the amount of OGX token that can be purchased. /// @param ethAmount Amount of Ether in WEI to purchase OGX. /// @return Amount of LKC token to purchase function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) { uint256 tokenBase = ethAmount.mul(BASE_RATE); uint8 roundNum = currentRoundIndex(); tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum])); while(tokens.add(totalSupply) > roundCaps[roundNum] && roundNum < 4){ roundNum++; tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum])); } } /// @dev Determine the current sale round /// @return integer representing the index of the current sale round function currentRoundIndex() internal view returns (uint8 roundNum) { roundNum = currentRoundIndexByDate(); /// round determined by conjunction of both time and total sold tokens while(roundNum < 4 && totalSupply > roundCaps[roundNum]) { roundNum++; } } /// @dev Determine the current sale tier. /// @return the index of the current sale tier by date. function currentRoundIndexByDate() internal view returns (uint8 roundNum) { require(now <= date14June2018); if(now > dateSaleR3) return 4; if(now > dateSaleR2) return 3; if(now > dateSaleR1) return 2; if(now > datePreSale) return 1; else return 0; } /// @dev Closes the sale, issues the team tokens and burns the unsold function close() public onlyOwner beforeEnd { /// Company team advisor and group tokens are equal to 37.5% uint256 amount_lockedTokens = 300000000; // No decimals uint256 lockedTokens = amount_lockedTokens* 10**uint256(decimals); // 300M Reserve for Founder and team are added to the locked tokens //resevred tokens are available from the beginning 25% uint256 reservedTokens = 100000000* 10**uint256(decimals); // 100M Reserve for parner //Sum tokens of locked and Reserved tokens uint256 sumlockedAndReservedTokens = lockedTokens + reservedTokens; //Init fegment uint256 fagmentSale = 0* 10**uint256(decimals); // 0 fegment Sale /// check for rounding errors when cap is reached if(totalSupply.add(sumlockedAndReservedTokens) > HARD_CAP) { sumlockedAndReservedTokens = HARD_CAP.sub(totalSupply); } //issueLockedTokens(lockedTokens); //----------------------------------------------- // Locked until Loop calculat uint256 _total_lockedTokens =0; for (uint256 i = 0; i < lockedTillPercentages.length; i = i.add(1)) { _total_lockedTokens =0; _total_lockedTokens = amount_lockedTokens.mul(lockedTillPercentages[i])* 10**uint256(decimals)/100; //Locked add % of Token amount locked issueLockedTokensCustom( _total_lockedTokens, dateTokensLockedTills[i] ); } //--------------------------------------------------- issueReservedTokens(reservedTokens); /// increase token total supply totalSupply = totalSupply.add(sumlockedAndReservedTokens); /// burn the unallocated tokens - no more tokens can be issued after this line tokenSaleClosed = true; /// forward the raised funds to the contract creator owner.transfer(this.balance); } /** * issue the tokens for the team and the foodout group. * tokens are locked for 1 years. * @param lockedTokens the amount of tokens to the issued and locked * */ function issueLockedTokens( uint lockedTokens) internal{ /// team tokens are locked until this date (01.01.2019) TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, dateTeamTokensLockedTill); timelockContractAddress = address(lockedTeamTokens); balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens); /// fire event when tokens issued Transfer(address(0), timelockContractAddress, lockedTokens); } function issueLockedTokensCustom( uint lockedTokens , uint64 _dateTokensLockedTill) internal{ /// team tokens are locked until this date (01.01.2019) TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, _dateTokensLockedTill); timelockContractAddress = address(lockedTeamTokens); balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens); /// fire event when tokens issued Transfer(address(0), timelockContractAddress, lockedTokens); } /** * issue the tokens for Reserved * @param reservedTokens & bounty Tokens the amount of tokens to be issued * */ function issueReservedTokens(uint reservedTokens) internal{ balances[owner] = reservedTokens; Transfer(address(0), owner, reservedTokens); } // Transfer limited by the tradingOpen modifier (time is 14 July 2018 or later) function transferFrom(address _from, address _to, uint256 _value) public tradingOpen returns (bool) { return super.transferFrom(_from, _to, _value); } /// Transfer limited by the tradingOpen modifier (time is 14 July 2018 or later) function transfer(address _to, uint256 _value) public tradingOpen returns (bool) { return super.transfer(_to, _value); } }
300M Reserve for Founder and team are added to the locked tokens
uint256 lockedTokens = amount_lockedTokens* 10**uint256(decimals);
1,075,855
[ 1, 19249, 49, 1124, 6527, 364, 478, 465, 765, 471, 5927, 854, 3096, 358, 326, 8586, 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 ]
[ 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, 3639, 2254, 5034, 8586, 5157, 273, 3844, 67, 15091, 5157, 14, 1728, 636, 11890, 5034, 12, 31734, 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 ]
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract Budget is Ownable { using EnumerableSet for EnumerableSet.AddressSet; /// @notice Maximum recipient count. uint256 public constant MAXIMUM_RECIPIENT_COUNT = 200; struct Expenditure { // Recipient address. address recipient; // Minimum balance at which budget allocation is performed. uint256 min; // Target balance at budget allocation. uint256 target; } /// @notice Expenditure item to address. mapping(address => Expenditure) public expenditures; /// @dev Recipients addresses list. EnumerableSet.AddressSet internal _recipients; /// @dev Withdrawal balance of recipients. mapping(address => uint256) public balanceOf; /// @notice Total withdrawal balance. uint256 public totalSupply; event ExpenditureChanged(address indexed recipient, uint256 min, uint256 target); event Withdrawal(address indexed recipient, uint256 amount); // solhint-disable-next-line no-empty-blocks receive() external payable {} /** * @notice Change expenditure item. * @param recipient Recipient address. * @param min Minimal balance for payment. * @param target Target balance. */ function changeExpenditure( address recipient, uint256 min, uint256 target ) external onlyOwner { require(min <= target, "Budget::changeExpenditure: minimal balance should be less or equal target balance"); require(recipient != address(0), "Budget::changeExpenditure: invalid recipient"); expenditures[recipient] = Expenditure(recipient, min, target); if (target > 0) { _recipients.add(recipient); require( _recipients.length() <= MAXIMUM_RECIPIENT_COUNT, "Budget::changeExpenditure: recipient must not exceed maximum count" ); } else { totalSupply -= balanceOf[recipient]; balanceOf[recipient] = 0; _recipients.remove(recipient); } emit ExpenditureChanged(recipient, min, target); } /** * @notice Transfer ETH to recipient. * @param recipient Recipient. * @param amount Transfer amount. */ function transferETH(address payable recipient, uint256 amount) external onlyOwner { require(amount > 0, "Budget::transferETH: negative or zero amount"); require(recipient != address(0), "Budget::transferETH: invalid recipient"); require(amount <= address(this).balance - totalSupply, "Budget::transferETH: transfer amount exceeds balance"); recipient.transfer(amount); } /** * @notice Return all recipients addresses. * @return Recipients addresses. */ function recipients() external view returns (address[] memory) { address[] memory result = new address[](_recipients.length()); for (uint256 i = 0; i < _recipients.length(); i++) { result[i] = _recipients.at(i); } return result; } /** * @notice Return balance deficit of recipient. * @param recipient Target recipient. * @return Balance deficit of recipient. */ function deficitTo(address recipient) public view returns (uint256) { require(_recipients.contains(recipient), "Budget::deficitTo: recipient not in expenditure item"); uint256 availableBalance = recipient.balance + balanceOf[recipient]; if (availableBalance >= expenditures[recipient].min) return 0; return expenditures[recipient].target - availableBalance; } /** * @notice Return summary balance deficit of all recipients. * @return Summary balance deficit of all recipients. */ function deficit() public view returns (uint256) { uint256 result; for (uint256 i = 0; i < _recipients.length(); i++) { result += deficitTo(_recipients.at(i)); } return result; } /** * @notice Pay ETH to all recipients with balance deficit. */ function pay() external { for (uint256 i = 0; i < _recipients.length(); i++) { uint256 budgetBalance = address(this).balance - totalSupply; address recipient = _recipients.at(i); uint256 amount = deficitTo(recipient); if (amount == 0 || budgetBalance < amount) continue; balanceOf[recipient] += amount; totalSupply += amount; } } /** * @notice Withdraw ETH to recipient. */ function withdraw() external { address payable recipient = payable(_msgSender()); uint256 amount = balanceOf[recipient]; require(amount > 0, "Budget::withdraw: transfer amount exceeds balance"); balanceOf[recipient] = 0; totalSupply -= amount; recipient.transfer(amount); emit Withdrawal(recipient, amount); } }
* @notice Return all recipients addresses. @return Recipients addresses./
function recipients() external view returns (address[] memory) { address[] memory result = new address[](_recipients.length()); for (uint256 i = 0; i < _recipients.length(); i++) { result[i] = _recipients.at(i); } return result; }
1,775,577
[ 1, 990, 777, 12045, 6138, 18, 327, 868, 15079, 6138, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 12045, 1435, 3903, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 565, 1758, 8526, 3778, 563, 273, 394, 1758, 8526, 24899, 27925, 18, 2469, 10663, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 27925, 18, 2469, 5621, 277, 27245, 288, 203, 1377, 563, 63, 77, 65, 273, 389, 27925, 18, 270, 12, 77, 1769, 203, 565, 289, 203, 203, 565, 327, 563, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "ds-test/test.sol"; import {TokenERC20} from "./test/utils/tokens/TokenERC20.sol"; import {Staking} from "./Staking.sol"; import {Hevm} from "./test/utils/Hevm.sol"; import {PRBProxy} from "@prb-proxy/contracts/PRBProxy.sol"; import {Batching} from "./batching/Batching.sol"; contract BatchingTest is DSTest { TokenERC20 internal tokenerc20; Staking internal staking; Hevm internal hevm = Hevm(HEVM_ADDRESS); Batching internal batching = new Batching(); PRBProxy internal proxy = new PRBProxy(); function setUp() public { tokenerc20 = new TokenERC20("Mock Token", "MOCK"); staking = new Staking(address(tokenerc20)); } function test_DepositWithdrawValueDirectly() public { uint amount = 100; tokenerc20.mint(address(this), amount); tokenerc20.approve(address(staking), amount); staking.deposit(amount); uint warpSeconds = 5; hevm.warp(block.timestamp + warpSeconds); staking.withdraw(amount); uint rewardAmount = staking.balanceOf(address(this)); assertEq(rewardAmount, amount * staking.rewardPerSecond() * warpSeconds); } function test_DepositAndWithdrawContract() public { uint amount = 100; bool ok; bytes memory data; // Create tokens tokenerc20.mint(address(this), amount); // Deposit tokens (ok, data) = address(batching).delegatecall( abi.encodeWithSelector( batching.deposit.selector, tokenerc20, staking, amount ) ); assertTrue(ok); assertTrue(keccak256(data) == keccak256(bytes(""))); // Travel in time uint warpSeconds = 5; hevm.warp(block.timestamp + warpSeconds); // Withdraw tokens and reward (ok, data) = address(batching).delegatecall( abi.encodeWithSelector( batching.withdraw.selector, staking, amount ) ); uint rewardAmount = staking.balanceOf(address(this)); assertEq(rewardAmount, amount * staking.rewardPerSecond() * warpSeconds); } function test_DepositAndWithdrawProxy() public { uint amount = 100; // Create tokens tokenerc20.mint(address(proxy), amount); // Deposit tokens proxy.execute( address(batching), abi.encodeWithSelector( batching.deposit.selector, tokenerc20, staking, amount ) ); // Travel in time uint warpSeconds = 5; hevm.warp(block.timestamp + warpSeconds); // Withdraw tokens and reward proxy.execute( address(batching), abi.encodeWithSelector( batching.withdraw.selector, staking, amount ) ); uint rewardAmount = staking.balanceOf(address(proxy)); assertEq(rewardAmount, amount * staking.rewardPerSecond() * warpSeconds); } }
Create tokens Deposit tokens Travel in time Withdraw tokens and reward
function test_DepositAndWithdrawProxy() public { uint amount = 100; tokenerc20.mint(address(proxy), amount); proxy.execute( address(batching), abi.encodeWithSelector( batching.deposit.selector, tokenerc20, staking, amount ) ); uint warpSeconds = 5; hevm.warp(block.timestamp + warpSeconds); proxy.execute( address(batching), abi.encodeWithSelector( batching.withdraw.selector, staking, amount ) ); uint rewardAmount = staking.balanceOf(address(proxy)); assertEq(rewardAmount, amount * staking.rewardPerSecond() * warpSeconds); }
15,805,303
[ 1, 1684, 2430, 4019, 538, 305, 2430, 2197, 941, 316, 813, 3423, 9446, 2430, 471, 19890, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 1842, 67, 758, 1724, 1876, 1190, 9446, 3886, 1435, 1071, 288, 203, 3639, 2254, 3844, 273, 2130, 31, 203, 203, 3639, 946, 708, 71, 3462, 18, 81, 474, 12, 2867, 12, 5656, 3631, 3844, 1769, 203, 203, 3639, 2889, 18, 8837, 12, 203, 5411, 1758, 12, 5303, 310, 3631, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 203, 7734, 2581, 310, 18, 323, 1724, 18, 9663, 16, 203, 7734, 946, 708, 71, 3462, 16, 203, 7734, 384, 6159, 16, 203, 7734, 3844, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 2254, 341, 11441, 6762, 273, 1381, 31, 203, 3639, 3904, 3489, 18, 905, 84, 12, 2629, 18, 5508, 397, 341, 11441, 6762, 1769, 203, 203, 3639, 2889, 18, 8837, 12, 203, 5411, 1758, 12, 5303, 310, 3631, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 203, 7734, 2581, 310, 18, 1918, 9446, 18, 9663, 16, 203, 7734, 384, 6159, 16, 203, 7734, 3844, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 2254, 19890, 6275, 273, 384, 6159, 18, 12296, 951, 12, 2867, 12, 5656, 10019, 203, 3639, 1815, 19508, 12, 266, 2913, 6275, 16, 3844, 380, 384, 6159, 18, 266, 2913, 2173, 8211, 1435, 380, 341, 11441, 6762, 1769, 540, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xA543de081e1c3065c75bc8Cf14a3bb14c5abeE36/sources/contracts/slopes/Slopes.sol
Withdraw LP tokens and earned PWDR from Accumulation. Withdrawing won't work until pwdrPoolActive == true Claim any pending PWDR and Tokens
function withdraw(uint256 _pid, uint256 _amount) public SlopesActive NonZeroAmount(_amount) { UserInfo storage user = userInfo[_pid][msg.sender]; require(user.staked >= _amount, "withdraw: not good"); updatePool(_pid); _claimRewardsFromPool(_pid, msg.sender); PoolInfo memory pool = poolInfo[_pid]; user.staked = user.staked.sub(_amount); user.rewardDebt = user.staked.mul(pool.accPwdrPerShare).div(1e12); user.tokenRewardDebt = user.staked.mul(pool.accTokenPerShare).div(1e12); if (_pid == 0) { _safeTokenTransfer(pool.lpToken, msg.sender, _amount); _safeTokenTransfer(pool.token, msg.sender, _amount); } emit Withdraw(msg.sender, _pid, _amount); }
8,588,407
[ 1, 1190, 9446, 511, 52, 2430, 471, 425, 1303, 329, 453, 59, 6331, 628, 15980, 5283, 367, 18, 3423, 9446, 310, 8462, 1404, 1440, 3180, 8772, 3069, 2864, 3896, 422, 638, 18381, 1281, 4634, 453, 59, 6331, 471, 13899, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 7010, 3639, 1071, 203, 3639, 348, 16884, 281, 3896, 203, 3639, 3858, 7170, 6275, 24899, 8949, 13, 203, 565, 288, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 334, 9477, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 540, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 203, 3639, 389, 14784, 17631, 14727, 1265, 2864, 24899, 6610, 16, 1234, 18, 15330, 1769, 203, 203, 3639, 8828, 966, 3778, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 203, 3639, 729, 18, 334, 9477, 273, 729, 18, 334, 9477, 18, 1717, 24899, 8949, 1769, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 334, 9477, 18, 16411, 12, 6011, 18, 8981, 52, 91, 3069, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 3639, 729, 18, 2316, 17631, 1060, 758, 23602, 273, 729, 18, 334, 9477, 18, 16411, 12, 6011, 18, 8981, 1345, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 203, 3639, 309, 261, 67, 6610, 422, 374, 13, 288, 203, 5411, 389, 4626, 1345, 5912, 12, 6011, 18, 9953, 1345, 16, 1234, 18, 15330, 16, 389, 8949, 1769, 203, 5411, 389, 4626, 1345, 5912, 12, 6011, 18, 2316, 16, 1234, 18, 15330, 16, 389, 8949, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 1769, 2 ]
./full_match/1/0xA5E2F5fcEEEA67C07b317c51F3741d2AA0775058/sources/contracts/ERC721Comet.sol
* @title ERC721Comet @author Orange Comet @notice Orange Comet standard ERC721 contract/ The royalty percentage as a percent (e.g. 10 for 10%) The max supply of tokens in this contract. The beneficiary wallet. The royalties wallet.
abstract contract ERC721Comet is ERC721A, Uri, ICometEvents, IERC2981 { bytes32 internal _provenanceHash; uint256 internal _royaltyPercent; uint256 internal _maxSupply; address internal _beneficiary; address internal _royalties; constructor( string memory name, string memory symbol ╭━━━╮╱╱╱╱╱╱╱╱╱╱╱╱╱╱╭━━━╮╱╱╱╱╱╱╱╱╭╮ pragma solidity ^0.8.9; import { IERC2981, IERC165 } from "@openzeppelin/contracts/interfaces/IERC2981.sol"; ) ERC721A(name, symbol) { _royaltyPercent = 10; _royalties = owner(); _beneficiary = owner(); } function setProvenanceHash(bytes32 value) external onlyOwner { _provenanceHash = value; } function provenanceHash() external view returns (bytes32) { return _provenanceHash; } function beneficiary() external view returns (address) { return _beneficiary; } function royalties() external view returns (address) { return _royalties; } function maxSupply() external view returns (uint256) { return _maxSupply; } function setBeneficiary(address wallet) public onlyOwner { _beneficiary = wallet; } function setMaxSupply(uint256 value) public onlyOwner { _maxSupply = value; emit MaxSupplyUpdated(value); } function setRoyalties(address wallet) public onlyOwner { _royalties = wallet; } function setRoyaltyPercent(uint256 value) external onlyOwner { _royaltyPercent = value; } function setConfig( uint256 newMaxSupply, address newRoyalties, address newBeneficiary, string memory newBaseURI, string memory newContractURI ) external onlyOwner { require( _totalMinted() == 0, "Cannot set config after minting has begun" ); setMaxSupply(newMaxSupply); setRoyalties(newRoyalties); setBeneficiary(newBeneficiary); setBaseURI(newBaseURI); setContractURI(newContractURI); emit ContractConfigUpdated( newMaxSupply, newRoyalties, newBeneficiary, newBaseURI, newContractURI ); } function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC721A, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } function _startTokenId() internal pure virtual override returns (uint256) { return 1; } }
8,329,516
[ 1, 654, 39, 27, 5340, 799, 278, 225, 2965, 726, 1286, 278, 225, 2965, 726, 1286, 278, 4529, 4232, 39, 27, 5340, 6835, 19, 1021, 721, 93, 15006, 11622, 487, 279, 5551, 261, 73, 18, 75, 18, 1728, 364, 1728, 9, 13, 1021, 943, 14467, 434, 2430, 316, 333, 6835, 18, 1021, 27641, 74, 14463, 814, 9230, 18, 1021, 721, 93, 2390, 606, 9230, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 17801, 6835, 4232, 39, 27, 5340, 799, 278, 353, 4232, 39, 27, 5340, 37, 16, 10693, 16, 467, 799, 278, 3783, 16, 467, 654, 39, 5540, 11861, 288, 203, 565, 1731, 1578, 2713, 389, 25630, 2310, 31, 203, 203, 565, 2254, 5034, 2713, 389, 3800, 15006, 8410, 31, 203, 203, 565, 2254, 5034, 2713, 389, 1896, 3088, 1283, 31, 203, 203, 565, 1758, 2713, 389, 70, 4009, 74, 14463, 814, 31, 203, 203, 565, 1758, 2713, 389, 3800, 2390, 606, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 203, 163, 248, 260, 163, 247, 228, 163, 247, 228, 163, 247, 228, 163, 248, 111, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 260, 163, 247, 228, 163, 247, 228, 163, 247, 228, 163, 248, 111, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 114, 163, 248, 260, 163, 248, 111, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 29, 31, 203, 5666, 288, 467, 654, 39, 5540, 11861, 16, 467, 654, 39, 28275, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 15898, 19, 45, 654, 39, 5540, 11861, 18, 18281, 14432, 203, 565, 262, 4232, 39, 2 ]
./full_match/1/0xE60a57cc57b51C4e801Ee8a0E6Df675F94abC0af/sources/contracts/ShopXReserveNFT.sol
* @notice Fails on calls with no `msg.data` but with `msg.value`/
receive() external payable { revert("Bad Call: ETH should be sent to mint() function."); }
4,887,294
[ 1, 30800, 603, 4097, 598, 1158, 1375, 3576, 18, 892, 68, 1496, 598, 1375, 3576, 18, 1132, 68, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 6798, 1435, 3903, 8843, 429, 288, 203, 565, 15226, 2932, 6434, 3049, 30, 512, 2455, 1410, 506, 3271, 358, 312, 474, 1435, 445, 1199, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x5Bd7b9cD17cee4d2Fae01D9695e83098CF409488/sources/Queue.sol
/Address for promo expencesPercent for promo expencesBonus prizeThe deposit structure holds all the info about the deposit made
contract Queue { address constant private PROMO1 = 0x0569E1777f2a7247D27375DB1c6c2AF9CE9a9C15; address constant private PROMO2 = 0xF892380E9880Ad0843bB9600D060BA744365EaDf; address constant private PROMO3 = 0x35aAF2c74F173173d28d1A7ce9d255f639ac1625; address constant private PRIZE = 0xa93E50526B63760ccB5fAD6F5107FA70d36ABC8b; uint constant public PROMO_PERCENT = 2; uint constant public BONUS_PERCENT = 3; struct Deposit { } function () public payable { require(block.number >= 6624911); if(msg.value > 0){ queue.push( Deposit(msg.sender, msg.value, 0) ); depositNumber[msg.sender] = queue.length; totalInvested += msg.value; uint promo1 = msg.value*PROMO_PERCENT/100; PROMO1.send(promo1); uint promo2 = msg.value*PROMO_PERCENT/100; PROMO2.send(promo2); uint promo3 = msg.value*PROMO_PERCENT/100; PROMO3.send(promo3); uint prize = msg.value*BONUS_PERCENT/100; PRIZE.send(prize); pay(); } } function () public payable { require(block.number >= 6624911); if(msg.value > 0){ queue.push( Deposit(msg.sender, msg.value, 0) ); depositNumber[msg.sender] = queue.length; totalInvested += msg.value; uint promo1 = msg.value*PROMO_PERCENT/100; PROMO1.send(promo1); uint promo2 = msg.value*PROMO_PERCENT/100; PROMO2.send(promo2); uint promo3 = msg.value*PROMO_PERCENT/100; PROMO3.send(promo3); uint prize = msg.value*BONUS_PERCENT/100; PRIZE.send(prize); pay(); } } function pay() internal { uint money = address(this).balance; uint multiplier = 120; for (uint i = 0; i < queue.length; i++){ uint totalPayout = dep.deposit * multiplier / 100; uint leftPayout; if (totalPayout > dep.payout) { leftPayout = totalPayout - dep.payout; } if (leftPayout > 0) { money -= leftPayout; } delete queue[idx]; } } function pay() internal { uint money = address(this).balance; uint multiplier = 120; for (uint i = 0; i < queue.length; i++){ uint totalPayout = dep.deposit * multiplier / 100; uint leftPayout; if (totalPayout > dep.payout) { leftPayout = totalPayout - dep.payout; } if (leftPayout > 0) { money -= leftPayout; } delete queue[idx]; } } function pay() internal { uint money = address(this).balance; uint multiplier = 120; for (uint i = 0; i < queue.length; i++){ uint totalPayout = dep.deposit * multiplier / 100; uint leftPayout; if (totalPayout > dep.payout) { leftPayout = totalPayout - dep.payout; } if (leftPayout > 0) { money -= leftPayout; } delete queue[idx]; } } function pay() internal { uint money = address(this).balance; uint multiplier = 120; for (uint i = 0; i < queue.length; i++){ uint totalPayout = dep.deposit * multiplier / 100; uint leftPayout; if (totalPayout > dep.payout) { leftPayout = totalPayout - dep.payout; } if (leftPayout > 0) { money -= leftPayout; } delete queue[idx]; } } depositNumber[dep.depositor] = 0; } else{ }
15,676,122
[ 1, 19, 1887, 364, 3012, 83, 1329, 2369, 8410, 364, 3012, 83, 1329, 2369, 38, 22889, 846, 554, 1986, 443, 1724, 3695, 14798, 777, 326, 1123, 2973, 326, 443, 1724, 7165, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7530, 288, 203, 203, 565, 1758, 5381, 3238, 453, 3942, 51, 21, 273, 374, 92, 20, 4313, 29, 41, 4033, 4700, 74, 22, 69, 27, 3247, 27, 40, 5324, 23, 5877, 2290, 21, 71, 26, 71, 22, 6799, 29, 1441, 29, 69, 29, 39, 3600, 31, 203, 202, 2867, 5381, 3238, 453, 3942, 51, 22, 273, 374, 16275, 6675, 4366, 3672, 41, 10689, 3672, 1871, 20, 5193, 23, 70, 38, 10525, 713, 40, 20, 4848, 12536, 5608, 24, 5718, 25, 41, 69, 40, 74, 31, 203, 202, 2867, 5381, 3238, 453, 3942, 51, 23, 202, 33, 374, 92, 4763, 69, 6799, 22, 71, 5608, 42, 31331, 31331, 72, 6030, 72, 21, 37, 27, 311, 29, 72, 10395, 74, 21607, 1077, 2313, 2947, 31, 203, 202, 2867, 5381, 3238, 10365, 3794, 202, 33, 374, 6995, 11180, 41, 3361, 25, 5558, 38, 4449, 27, 4848, 952, 38, 25, 74, 1880, 26, 42, 25, 23054, 2046, 7301, 72, 5718, 26904, 28, 70, 31, 203, 202, 203, 565, 2254, 5381, 1071, 453, 3942, 51, 67, 3194, 19666, 273, 576, 31, 203, 377, 203, 565, 2254, 5381, 1071, 605, 673, 3378, 67, 3194, 19666, 273, 890, 31, 203, 1082, 203, 203, 203, 203, 565, 1958, 4019, 538, 305, 288, 203, 565, 289, 203, 203, 203, 565, 445, 1832, 1071, 8843, 429, 288, 203, 540, 203, 3639, 2583, 12, 2629, 18, 2696, 1545, 22342, 3247, 29, 2499, 1769, 203, 203, 3639, 309, 12, 3576, 18, 1132, 405, 374, 15329, 203, 203, 2398, 203, 5411, 2389, 18, 6206, 12, 4019, 2 ]
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ApproveAndCallReceiver { function receiveApproval( address _from, uint256 _amount, address _token, bytes _data ) public; } //normal contract. already compiled as bin contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } //block for check//bool private initialed = false; address public controller; constructor() public { controller = msg.sender; } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } //abstract contract. used for interface contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable public returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } contract ERC20Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; //function totalSupply() public constant returns (uint256 balance); /// @param _owner The address from which the balance will be retrieved /// @return The balance mapping (address => uint256) public balanceOf; //function balanceOf(address _owner) public 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) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent mapping (address => mapping (address => uint256)) public allowance; //function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract TokenI is ERC20Token, Controlled { string public name; //The Token&#39;s name: e.g. DigixDAO Tokens uint8 public decimals = 18; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP // ERC20 Methods /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall( address _spender, uint256 _amount, bytes _extraData ) public returns (bool success); // Generate and destroy tokens /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) public returns (bool); /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) public returns (bool); /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public; // Safety Methods /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _tokens The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. /// @param _to The address of the token will be send. e.g. some user or exchange function claimTokens(address[] _tokens, address _to) public; // Events event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); } contract Token is TokenI { using SafeMath for uint256; string public techProvider = "WeYii Tech"; string public officialSite = "http://www.beautybloc.io"; //owner是最初的币持有者。对比之下,controller 是合约操作者 address public owner; struct FreezeInfo { address user; uint256 amount; } //Key1: step(募资阶段); Key2: user sequence(用户序列) mapping (uint8 => mapping (uint32 => FreezeInfo)) public freezeOf; //所有锁仓,key 使用序号向上增加,方便程序查询。 mapping (uint8 => uint32) public lastFreezeSeq; //最后的 freezeOf 键值。key: step; value: sequence bool public transfersEnabled = true; /* This generates a public event on the blockchain that will notify clients */ /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); event TransferMulti(uint256 userLen, uint256 valueAmount); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string tokenName, string tokenSymbol, address initialOwner ) public { owner = initialOwner; totalSupply = initialSupply * uint256(10) ** decimals; balanceOf[owner] = totalSupply; name = tokenName; symbol = tokenSymbol; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier ownerOrController() { require(msg.sender == owner || msg.sender == controller); _; } modifier transable(){ require(transfersEnabled == true); _; } modifier realUser(address user){ require(user != 0x0); _; } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) { return false; } assembly { size := extcodesize(_addr) } return size>0; } /* Send coins */ function transfer(address _to, uint256 _value) realUser(_to) transable public returns (bool) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) transable public returns (bool success) { require(_value == 0 || (allowance[msg.sender][_spender] == 0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @notice `msg.sender` approves `_spender` to send `_amount` tokens on * its behalf, and then a function is triggered in the contract that is * being approved, `_spender`. This allows users to use their tokens to * interact with contracts in one function call instead of two * @param _spender The address of the contract able to transfer the tokens * @param _amount The amount of tokens to be approved for transfer * @return True if the function call was successful */ function approveAndCall(address _spender, uint256 _amount, bytes _extraData) transable public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallReceiver(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) realUser(_from) realUser(_to) transable public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function transferMulti(address[] _to, uint256[] _value) transable public returns (uint256 amount){ require(_to.length == _value.length && _to.length <= 1024); uint256 balanceOfSender = balanceOf[msg.sender]; uint256 len = _to.length; for(uint256 j; j<len; j++){ amount = amount.add(_value[j]); } balanceOf[msg.sender] = balanceOfSender.sub(amount); address _toI; uint256 _valueI; for(uint256 i; i<len; i++){ _toI = _to[i]; _valueI = _value[i]; balanceOf[_toI] = balanceOf[_toI].add(_valueI); emit Transfer(msg.sender, _toI, _valueI); } emit TransferMulti(len, amount); } //对多人按相同数量转账 function transferMultiSameVaule(address[] _to, uint256 _value) transable public returns (bool success){ uint256 len = _to.length; uint256 amount = _value.mul(len); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); //this will check enough automatically address _toI; for(uint256 i; i<len; i++){ _toI = _to[i]; balanceOf[_toI] = balanceOf[_toI].add(_value); emit Transfer(msg.sender, _toI, _value); } emit TransferMulti(len, amount); return true; } //只owner和controller 才能冻结账户 function freeze(address _user, uint256 _value, uint8 _step) ownerOrController public returns (bool success) { require(balanceOf[_user] >= _value); balanceOf[_user] = balanceOf[_user] - _value; freezeOf[_step][lastFreezeSeq[_step]] = FreezeInfo({user:_user, amount:_value}); lastFreezeSeq[_step]++; emit Freeze(_user, _value); return true; } //为用户解锁账户资金 function unFreeze(uint8 _step) ownerOrController public returns (bool unlockOver) { uint32 _end = lastFreezeSeq[_step]; require(_end > 0); unlockOver = (_end <= 99); uint32 _start = (_end > 99) ? _end-100 : 0; for(; _end>_start; _end--){ FreezeInfo storage fInfo = freezeOf[_step][_end-1]; uint256 _amount = fInfo.amount; balanceOf[fInfo.user] += _amount; delete freezeOf[_step][_end-1]; lastFreezeSeq[_step]--; emit Unfreeze(fInfo.user, _amount); } } //accept ether function() payable public { //屏蔽控制方的合约类型检查,以兼容发行方无控制合约的情况。 require(isContract(controller)); bool proxyPayment = TokenController(controller).proxyPayment.value(msg.value)(msg.sender); require(proxyPayment); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _user The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _user, uint _amount) onlyController public returns (bool) { require(balanceOf[owner] >= _amount); balanceOf[_user] += _amount; balanceOf[owner] -= _amount; emit Transfer(0, _user, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _user The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _user, uint _amount) onlyController public returns (bool) { require(balanceOf[_user] >= _amount); balanceOf[owner] += _amount; balanceOf[_user] -= _amount; emit Transfer(_user, 0, _amount); emit Burn(_user, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) ownerOrController public { transfersEnabled = _transfersEnabled; } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// set to 0 in case you want to extract ether. function claimTokens(address[] tokens, address to) onlyOwner public { if(to == 0x0){ to = owner; } address _token; uint256 balance; uint256 len = tokens.length; for(uint256 i; i<len; i++){ _token = tokens[i]; if (_token == 0x0) { balance = address(this).balance; if(balance > 0){ to.transfer(balance); } }else{ ERC20Token token = ERC20Token(_token); balance = token.balanceOf(address(this)); token.transfer(to, balance); emit ClaimedTokens(_token, to, balance); } } } function changeOwner(address newOwner) onlyOwner public returns (bool) { balanceOf[newOwner] = balanceOf[owner].add(balanceOf[newOwner]); balanceOf[owner] = 0; owner = newOwner; return true; } }
A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) realUser(_from) realUser(_to) transable public returns (bool success) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
2,188,644
[ 1, 37, 6835, 7531, 358, 336, 326, 276, 9896, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 2863, 1299, 24899, 2080, 13, 2863, 1299, 24899, 869, 13, 906, 429, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x18c549526D3D2B675EB8CA7938FCF5050D6762cb/sources/DFTZToken.sol
* Set allowance for other address. Allows `_spender` to spend no more than `_value` tokens in your behalf. @param _spender The address authorized to spend. @param _value the max amount they can spend./
function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance[msg.sender][_spender] == 0)); allowance[msg.sender][_spender] = _value; return true; }
2,660,366
[ 1, 694, 1699, 1359, 364, 1308, 1758, 18, 25619, 1375, 67, 87, 1302, 264, 68, 358, 17571, 1158, 1898, 2353, 1375, 67, 1132, 68, 2430, 316, 3433, 12433, 6186, 18, 225, 389, 87, 1302, 264, 1021, 1758, 10799, 358, 17571, 18, 225, 389, 1132, 326, 943, 3844, 2898, 848, 17571, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 203, 3639, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12443, 67, 1132, 422, 374, 13, 747, 261, 5965, 1359, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 422, 374, 10019, 203, 3639, 1699, 1359, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x081C3D48E7C4CCE63E7BC838d83B8556B17261c6/sources/contracts/clipFinanceNFT.sol
If true, baseURI, will be set forever.
bool public baseURICommitted;
17,164,996
[ 1, 2047, 638, 16, 1026, 3098, 16, 903, 506, 444, 21238, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1026, 3098, 27813, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import '@openzeppelin/contracts/security/PullPayment.sol'; import './Governed.sol'; import './OwnerBalanceContributor.sol'; import './Macabris.sol'; import './Bank.sol'; /** * @title Macabris market contract, tracks bids and asking prices */ contract Market is Governed, OwnerBalanceContributor, PullPayment { // Macabris NFT contract Macabris public macabris; // Bank contract Bank public bank; // Mapping from token IDs to asking prices mapping(uint256 => uint) private asks; // Mapping of bidder addresses to bid amounts indexed by token IDs mapping(address => mapping(uint256 => uint)) private bids; // Mappings of prev/next bidder address in line for each token ID // Next bid is the smaller one, prev bid is the bigger one mapping(uint256 => mapping(address => address)) private nextBidders; mapping(uint256 => mapping(address => address)) private prevBidders; // Mapping of token IDs to the highest bidder address mapping(uint256 => address) private highestBidders; // Owner and bank fees for market operations in bps uint16 public ownerFee; uint16 public bankFee; /** * @dev Emitted when a bid is placed on a token * @param tokenId Token ID * @param bidder Bidder address * @param amount Bid amount in wei */ event Bid(uint256 indexed tokenId, address indexed bidder, uint amount); /** * @dev Emitted when a bid is canceled * @param tokenId Token ID * @param bidder Bidder address * @param amount Canceled bid amount in wei */ event BidCancellation(uint256 indexed tokenId, address indexed bidder, uint amount); /** * @dev Emitted when an asking price is set * @param tokenId Token ID * @param seller Token owner address * @param price Price in wei */ event Ask(uint256 indexed tokenId, address indexed seller, uint price); /** * @dev Emitted when the asking price is reset marking the token as no longer for sale * @param tokenId Token ID * @param seller Token owner address * @param price Canceled asking price in wei */ event AskCancellation(uint256 indexed tokenId, address indexed seller, uint price); /** * @dev Emitted when a token is sold via `sellForHighestBid` or `buyForAskingPrice` methods * @param tokenId Token ID * @param seller Seller address * @param buyer Buyer addres * @param price Price in wei */ event Sale(uint256 indexed tokenId, address indexed seller, address indexed buyer, uint price); /** * @param governanceAddress Address of the Governance contract * @param ownerBalanceAddress Address of the OwnerBalance contract * * Requirements: * - Governance contract must be deployed at the given address * - OwnerBalance contract must be deployed at the given address */ constructor( address governanceAddress, address ownerBalanceAddress ) Governed(governanceAddress) OwnerBalanceContributor(ownerBalanceAddress) {} /** * @dev Sets Macabris NFT contract address * @param macabrisAddress Address of Macabris NFT contract * * Requirements: * - the caller must have the boostrap permission * - Macabris contract must be deployed at the given address */ function setMacabrisAddress(address macabrisAddress) external canBootstrap(msg.sender) { macabris = Macabris(macabrisAddress); } /** * @dev Sets Bank contract address * @param bankAddress Address of Macabris NFT contract * * Requirements: * - the caller must have the bootstrap permission * - Bank contract must be deployed at the given address */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = Bank(bankAddress); } /** * @dev Sets owner's fee on market operations * @param _ownerFee Fee in bps * * Requirements: * - The caller must have canConfigure permission * - Owner fee should divide 10000 without a remainder * - Owner and bank fees should not add up to more than 10000 bps (100%) */ function setOwnerFee(uint16 _ownerFee) external canConfigure(msg.sender) { require(_ownerFee + bankFee < 10000, "The sum of owner and bank fees should be less than 10000 bps"); if (_ownerFee > 0) { require(10000 % _ownerFee == 0, "Owner fee amount must divide 10000 without a remainder"); } ownerFee = _ownerFee; } /** * @dev Sets bank's fee on market operations, that goes to the payouts pool * @param _bankFee Fee in bps * * Requirements: * - The caller must have canConfigure permission * - Bank fee should divide 10000 without a remainder * - Owner and bank fees should not add up to more than 10000 bps (100%) */ function setBankFee(uint16 _bankFee) external canConfigure(msg.sender) { require(ownerFee + _bankFee < 10000, "The sum of owner and bank fees should be less than 10000 bps"); if (_bankFee > 0) { require(10000 % _bankFee == 0, "Bank fee amount must divide 10000 without a remainder"); } bankFee = _bankFee; } /** * @dev Creates a new bid for a token * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Bid amount (`msg.value`) must be bigger than 0 * - Bid amount (`msg.value`) must be bigger than the current highest bid * - Bid amount (`msg.value`) must be lower than the current asking price * - Sender must not be the token owner * - Sender must not have an active bid for the token (use `cancelBid` before bidding again) * * Emits {Bid} event */ function bid(uint256 tokenId) external payable { require(msg.value > 0, "Bid amount invalid"); require(macabris.exists(tokenId), "Token does not exist"); require(macabris.ownerOf(tokenId) != msg.sender, "Can't bid on owned tokens"); require(bids[msg.sender][tokenId] == 0, "Bid already exists, cancel it before bidding again"); (, uint highestBidAmount) = getHighestBid(tokenId); require(msg.value > highestBidAmount, "Bid must be larger than the current highest bid"); uint askingPrice = getAskingPrice(tokenId); require(askingPrice == 0 || msg.value < askingPrice, "Bid must be smaller then the asking price"); bids[msg.sender][tokenId] = msg.value; nextBidders[tokenId][msg.sender] = highestBidders[tokenId]; prevBidders[tokenId][highestBidders[tokenId]] = msg.sender; highestBidders[tokenId] = msg.sender; emit Bid(tokenId, msg.sender, msg.value); } /** * @dev Cancels sender's currently active bid for the given token and returns the Ether * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Sender must have an active bid for the token * * Emits {BidCancellation} event */ function cancelBid(uint256 tokenId) public { require(macabris.exists(tokenId), "Token does not exist"); require(bids[msg.sender][tokenId] > 0, "Bid does not exist"); uint amount = bids[msg.sender][tokenId]; _removeBid(tokenId, msg.sender); _asyncTransfer(msg.sender, amount); emit BidCancellation(tokenId, msg.sender, amount); } /** * @dev Removes bid and does required houskeeping to maintain the bid queue * @param tokenId Token ID * @param bidder Bidder address */ function _removeBid(uint256 tokenId, address bidder) private { address prevBidder = prevBidders[tokenId][bidder]; address nextBidder = nextBidders[tokenId][bidder]; // If this bid was the highest one, the next one will become the highest if (prevBidder == address(0)) { highestBidders[tokenId] = nextBidder; } // If there are bigger bids than this, remove the link to this one as the next bid if (prevBidder != address(0)) { nextBidders[tokenId][prevBidder] = nextBidder; } // If there are smaller bids than this, remove the link to this one as the prev bid if (nextBidder != address(0)) { prevBidders[tokenId][nextBidder] = prevBidder; } delete bids[bidder][tokenId]; } /** * @dev Sets the asking price for the token (enabling instant buy ability) * @param tokenId Token ID * @param amount Asking price in wei * * Requirements: * - `tokenId` must exist * - Sender must be the owner of the token * - `amount` must be bigger than 0 * - `amount` must be bigger than the highest bid * * Emits {Ask} event */ function ask(uint256 tokenId, uint amount) external { // Also checks if the token exists require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender"); require(amount > 0, "Ask amount invalid"); (, uint highestBidAmount) = getHighestBid(tokenId); require(amount > highestBidAmount, "Ask amount must be larger than the highest bid"); asks[tokenId] = amount; emit Ask(tokenId, msg.sender, amount); } /** * @dev Removes asking price for the token (disabling instant buy ability) * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Sender must be the owner of the token * * Emits {AskCancellation} event */ function cancelAsk(uint256 tokenId) external { // Also checks if the token exists require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender"); uint askingPrice = asks[tokenId]; delete asks[tokenId]; emit AskCancellation(tokenId, msg.sender, askingPrice); } /** * @dev Sells token to the highest bidder * @param tokenId Token ID * @param amount Expected highest bid amount, fails if the actual bid amount does not match it * * Requirements: * - `tokenId` must exist * - Sender must be the owner of the token * - There must be at least a single bid for the token * * Emits {Sale} event */ function sellForHighestBid(uint256 tokenId, uint amount) external { // Also checks if the token exists require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender"); (address highestBidAddress, uint highestBidAmount) = getHighestBid(tokenId); require(highestBidAmount > 0, "There are no bids for the token"); require(amount == highestBidAmount, "Highest bid amount does not match given amount value"); delete asks[tokenId]; _removeBid(tokenId, highestBidAddress); _onSale(tokenId, msg.sender, highestBidAddress, highestBidAmount); } /** * @dev Buys token for the asking price * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Sender must not be the owner of the token * - Asking price must be set for the token * - `msg.value` must match the asking price * * Emits {Sale} event */ function buyForAskingPrice(uint256 tokenId) external payable { // Implicitly checks if the token exists address seller = macabris.ownerOf(tokenId); require(msg.sender != seller, "Can't buy owned tokens"); uint askingPrice = getAskingPrice(tokenId); require(askingPrice > 0, "Token is not for sale"); require(msg.value == askingPrice, "Transaction value does not match the asking price"); delete asks[tokenId]; // Cancel any bid to prevent a situation where an owner has a bid on own token if (getBidAmount(tokenId, msg.sender) > 0) { cancelBid(tokenId); } _onSale(tokenId, seller, msg.sender, askingPrice); } /** * @dev Notifes Macabris about the sale, transfers money to the seller and emits a Sale event * @param tokenId Token ID * @param seller Seller address * @param buyer Buyer address * @param price Sale price * * Emits {Sale} event */ function _onSale(uint256 tokenId, address seller, address buyer, uint price) private { uint ownerFeeAmount = _calculateFeeAmount(price, ownerFee); uint bankFeeAmount = _calculateFeeAmount(price, bankFee); uint priceAfterFees = price - ownerFeeAmount - bankFeeAmount; macabris.onMarketSale(tokenId, seller, buyer); bank.deposit{value: bankFeeAmount}(); _transferToOwnerBalance(ownerFeeAmount); _asyncTransfer(seller, priceAfterFees); emit Sale(tokenId, seller, buyer, price); } /** * @dev Calculates fee amount based on given price and fee in bps * @param price Price base for calculation * @param fee Fee in basis points * @return Fee amount in wei */ function _calculateFeeAmount(uint price, uint fee) private pure returns (uint) { // Fee might be zero, avoiding division by zero if (fee == 0) { return 0; } // Only using division to make sure there is no overflow of the return value. // This is the reason why fee must divide 10000 without a remainder, otherwise // because of integer division fee won't be accurate. return price / (10000 / fee); } /** * @dev Returns current asking price for which the token can be bought immediately * @param tokenId Token ID * @return Amount in wei, 0 if the token is currently not for sale */ function getAskingPrice(uint256 tokenId) public view returns (uint) { return asks[tokenId]; } /** * @dev Returns the highest bidder address and the bid amount for the given token * @param tokenId Token ID * @return Highest bidder address, 0 if not bid exists * @return Amount in wei, 0 if no bid exists */ function getHighestBid(uint256 tokenId) public view returns (address, uint) { address highestBidder = highestBidders[tokenId]; return (highestBidder, bids[highestBidder][tokenId]); } /** * @dev Returns bid amount for the given token and bidder address * @param tokenId Token ID * @param bidder Bidder address * @return Amount in wei, 0 if no bid exists * * Requirements: * - `tokenId` must exist */ function getBidAmount(uint256 tokenId, address bidder) public view returns (uint) { require(macabris.exists(tokenId), "Token does not exist"); return bids[bidder][tokenId]; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governed.sol'; import './Bank.sol'; /** * @title Contract tracking deaths of Macabris tokens */ contract Reaper is Governed { // Bank contract Bank public bank; // Mapping from token ID to time of death mapping (uint256 => int64) private _deaths; /** * @dev Emitted when a token is marked as dead * @param tokenId Token ID * @param timeOfDeath Time of death (unix timestamp) */ event Death(uint256 indexed tokenId, int64 timeOfDeath); /** * @dev Emitted when a previosly dead token is marked as alive * @param tokenId Token ID */ event Resurrection(uint256 indexed tokenId); /** * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor(address governanceAddress) Governed(governanceAddress) {} /** * @dev Sets Bank contract address * @param bankAddress Address of Bank contract * * Requirements: * - the caller must have the boostrap permission * - Bank contract must be deployed at the given address */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = Bank(bankAddress); } /** * @dev Marks token as dead and sets time of death * @param tokenId Token ID * @param timeOfDeath Tome of death (unix timestamp) * * Requirements: * - the caller must have permission to manage deaths * - `timeOfDeath` can't be 0 * * Note that tokenId doesn't have to be minted in order to be marked dead. * * Emits {Death} event */ function markDead(uint256 tokenId, int64 timeOfDeath) external canManageDeaths(msg.sender) { require(timeOfDeath != 0, "Time of death of 0 represents an alive token"); _deaths[tokenId] = timeOfDeath; bank.onTokenDeath(tokenId); emit Death(tokenId, timeOfDeath); } /** * @dev Marks token as alive * @param tokenId Token ID * * Requirements: * - the caller must have permission to manage deaths * - `tokenId` must be currently marked as dead * * Emits {Resurrection} event */ function markAlive(uint256 tokenId) external canManageDeaths(msg.sender) { require(_deaths[tokenId] != 0, "Token is not dead"); _deaths[tokenId] = 0; bank.onTokenResurrection(tokenId); emit Resurrection(tokenId); } /** * @dev Returns token's time of death * @param tokenId Token ID * @return Time of death (unix timestamp) or zero, if alive * * Note that any tokenId could be marked as dead, even not minted or not existant one. */ function getTimeOfDeath(uint256 tokenId) external view returns (int64) { return _deaths[tokenId]; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './OwnerBalance.sol'; /** * @title Allows allocating portion of the contract's funds to the owner balance */ abstract contract OwnerBalanceContributor { // OwnerBalance contract address address public immutable ownerBalanceAddress; uint public ownerBalanceDeposits; /** * @param _ownerBalanceAddress Address of the OwnerBalance contract */ constructor (address _ownerBalanceAddress) { ownerBalanceAddress = _ownerBalanceAddress; } /** * @dev Assigns given amount of contract funds to the owner's balance * @param amount Amount in wei */ function _transferToOwnerBalance(uint amount) internal { ownerBalanceDeposits += amount; } /** * @dev Allows OwnerBalance contract to withdraw deposits * @param ownerAddress Owner address to send funds to * * Requirements: * - caller must be the OwnerBalance contract */ function withdrawOwnerBalanceDeposits(address ownerAddress) external { require(msg.sender == ownerBalanceAddress, 'Caller must be the OwnerBalance contract'); uint currentBalance = ownerBalanceDeposits; ownerBalanceDeposits = 0; payable(ownerAddress).transfer(currentBalance); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governed.sol'; import './OwnerBalanceContributor.sol'; /** * @title Tracks owner's share of the funds in various Macabris contracts */ contract OwnerBalance is Governed { address public owner; // All three contracts, that contribute to the owner's balance OwnerBalanceContributor public release; OwnerBalanceContributor public bank; OwnerBalanceContributor public market; /** * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor(address governanceAddress) Governed(governanceAddress) {} /** * @dev Sets the release contract address * @param releaseAddress Address of the Release contract * * Requirements: * - the caller must have the bootstrap permission */ function setReleaseAddress(address releaseAddress) external canBootstrap(msg.sender) { release = OwnerBalanceContributor(releaseAddress); } /** * @dev Sets Bank contract address * @param bankAddress Address of the Bank contract * * Requirements: * - the caller must have the bootstrap permission */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = OwnerBalanceContributor(bankAddress); } /** * @dev Sets the market contract address * @param marketAddress Address of the Market contract * * Requirements: * - the caller must have the bootstrap permission */ function setMarketAddress(address marketAddress) external canBootstrap(msg.sender) { market = OwnerBalanceContributor(marketAddress); } /** * @dev Sets owner address where the funds will be sent during withdrawal * @param _owner Owner's address * * Requirements: * - sender must have canSetOwnerAddress permission * - address must not be 0 */ function setOwner(address _owner) external canSetOwnerAddress(msg.sender) { require(_owner != address(0), "Empty owner address is not allowed!"); owner = _owner; } /** * @dev Returns total available balance in all contributing contracts * @return Balance in wei */ function getBalance() external view returns (uint) { uint balance; balance += release.ownerBalanceDeposits(); balance += bank.ownerBalanceDeposits(); balance += market.ownerBalanceDeposits(); return balance; } /** * @dev Withdraws available balance to the owner address * * Requirements: * - owner address must be set * - sender must have canTriggerOwnerWithdraw permission */ function withdraw() external canTriggerOwnerWithdraw(msg.sender) { require(owner != address(0), "Owner address is not set"); release.withdrawOwnerBalanceDeposits(owner); bank.withdrawOwnerBalanceDeposits(owner); market.withdrawOwnerBalanceDeposits(owner); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import './Governed.sol'; import './Bank.sol'; contract Macabris is ERC721, Governed { // Release contract address, used to whitelist calls to `onRelease` method address public releaseAddress; // Market contract address, used to whitelist calls to `onMarketSale` method address public marketAddress; // Bank contract Bank public bank; // Base URI of the token's metadata string public baseUri; // Personas sha256 hash (all UTF-8 names with a "\n" char after each name, sorted by token ID) bytes32 public immutable hash; /** * @param _hash Personas sha256 hash (all UTF-8 names with a "\n" char after each name, sorted by token ID) * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor( bytes32 _hash, address governanceAddress ) ERC721('Macabris', 'MCBR') Governed(governanceAddress) { hash = _hash; } /** * @dev Sets the release contract address * @param _releaseAddress Address of the Release contract * * Requirements: * - the caller must have the bootstrap permission */ function setReleaseAddress(address _releaseAddress) external canBootstrap(msg.sender) { releaseAddress = _releaseAddress; } /** * @dev Sets the market contract address * @param _marketAddress Address of the Market contract * * Requirements: * - the caller must have the bootstrap permission */ function setMarketAddress(address _marketAddress) external canBootstrap(msg.sender) { marketAddress = _marketAddress; } /** * @dev Sets Bank contract address * @param bankAddress Address of the Bank contract * * Requirements: * - the caller must have the bootstrap permission * - Bank contract must be deployed at the given address */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = Bank(bankAddress); } /** * @dev Sets metadata base URI * @param _baseUri Base URI, token's ID will be appended at the end */ function setBaseUri(string memory _baseUri) external canConfigure(msg.sender) { baseUri = _baseUri; } /** * @dev Checks if the token exists * @param tokenId Token ID * @return True if token with given ID has been minted already, false otherwise */ function exists(uint256 tokenId) external view returns (bool) { return _exists(tokenId); } /** * @dev Overwrites to return base URI set by the contract owner */ function _baseURI() override internal view returns (string memory) { return baseUri; } function _transfer(address from, address to, uint256 tokenId) override internal { super._transfer(from, to, tokenId); bank.onTokenTransfer(tokenId, from, to); } function _mint(address to, uint256 tokenId) override internal { super._mint(to, tokenId); bank.onTokenTransfer(tokenId, address(0), to); } /** * @dev Registers new token after it's sold and revealed in the Release contract * @param tokenId Token ID * @param buyer Buyer address * * Requirements: * - The caller must be the Release contract * - `tokenId` must not exist * - Buyer cannot be the zero address * * Emits a {Transfer} event. */ function onRelease(uint256 tokenId, address buyer) external { require(msg.sender == releaseAddress, "Caller must be the Release contract"); // Also checks that the token does not exist and that the buyer is not 0 address. // Using unsafe mint to prevent a situation where a sale could not be revealed in the // realease contract, because the buyer address does not implement IERC721Receiver. _mint(buyer, tokenId); } /** * @dev Transfers token ownership after a sale on the Market contract * @param tokenId Token ID * @param seller Seller address * @param buyer Buyer address * * Requirements: * - The caller must be the Market contract * - `tokenId` must exist * - `seller` must be the owner of the token * - `buyer` cannot be the zero address * * Emits a {Transfer} event. */ function onMarketSale(uint256 tokenId, address seller, address buyer) external { require(msg.sender == marketAddress, "Caller must be the Market contract"); // Also checks if the token exists, if the seller is the current owner and that the buyer is // not 0 address. // Using unsafe transfer to prevent a situation where the token owner can't accept the // highest bid, because the bidder address does not implement IERC721Receiver. _transfer(seller, buyer, tokenId); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governance.sol'; /** * @title Provides permission check modifiers for child contracts */ abstract contract Governed { // Governance contract Governance public immutable governance; /** * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor (address governanceAddress) { governance = Governance(governanceAddress); } /** * @dev Throws if given address that doesn't have ManagesDeaths permission * @param subject Address to check permissions for, usually msg.sender */ modifier canManageDeaths(address subject) { require( governance.hasPermission(subject, Governance.Actions.ManageDeaths), "Governance: subject is not allowed to manage deaths" ); _; } /** * @dev Throws if given address that doesn't have Configure permission * @param subject Address to check permissions for, usually msg.sender */ modifier canConfigure(address subject) { require( governance.hasPermission(subject, Governance.Actions.Configure), "Governance: subject is not allowed to configure contracts" ); _; } /** * @dev Throws if given address that doesn't have Bootstrap permission * @param subject Address to check permissions for, usually msg.sender */ modifier canBootstrap(address subject) { require( governance.hasPermission(subject, Governance.Actions.Bootstrap), "Governance: subject is not allowed to bootstrap" ); _; } /** * @dev Throws if given address that doesn't have SetOwnerAddress permission * @param subject Address to check permissions for, usually msg.sender */ modifier canSetOwnerAddress(address subject) { require( governance.hasPermission(subject, Governance.Actions.SetOwnerAddress), "Governance: subject is not allowed to set owner address" ); _; } /** * @dev Throws if given address that doesn't have TriggerOwnerWithdraw permission * @param subject Address to check permissions for, usually msg.sender */ modifier canTriggerOwnerWithdraw(address subject) { require( governance.hasPermission(subject, Governance.Actions.TriggerOwnerWithdraw), "Governance: subject is not allowed to trigger owner withdraw" ); _; } /** * @dev Throws if given address that doesn't have StopPayouyts permission * @param subject Address to check permissions for, usually msg.sender */ modifier canStopPayouts(address subject) { require( governance.hasPermission(subject, Governance.Actions.StopPayouts), "Governance: subject is not allowed to stop payouts" ); _; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; /** * @title Manages address permissions to act on Macabris contracts */ contract Governance { enum Actions { Vote, Configure, SetOwnerAddress, TriggerOwnerWithdraw, ManageDeaths, StopPayouts, Bootstrap } // Stores permissions of an address struct Permissions { bool canVote; bool canConfigure; bool canSetOwnerAddress; bool canTriggerOwnerWithdraw; bool canManageDeaths; bool canStopPayouts; // Special permission that can't be voted in and only the deploying address receives bool canBootstrap; } // A call for vote to change address permissions struct CallForVote { // Address that will be assigned the permissions if the vote passes address subject; // Permissions to be assigned if the vote passes Permissions permissions; // Total number of votes for and against the permission change uint128 yeas; uint128 nays; } // A vote in a call for vote struct Vote { uint64 callForVoteIndex; bool yeaOrNay; } // Permissions of addresses mapping(address => Permissions) private permissions; // List of calls for a vote: callForVoteIndex => CallForVote, callForVoteIndex starts from 1 mapping(uint => CallForVote) private callsForVote; // Last registered call for vote of every address: address => callForVoteIndex mapping(address => uint64) private lastRegisteredCallForVote; // Votes of every address: address => Vote mapping(address => Vote) private votes; uint64 public resolvedCallsForVote; uint64 public totalCallsForVote; uint64 public totalVoters; /** * @dev Emitted when a new call for vote is registered * @param callForVoteIndex Index of the call for vote (1-based) * @param subject Subject address to change permissions to if vote passes * @param canVote Allow subject address to vote * @param canConfigure Allow subject address to configure prices, fees and base URI * @param canSetOwnerAddress Allows subject to change owner withdraw address * @param canTriggerOwnerWithdraw Allow subject address to trigger withdraw from owner's balance * @param canManageDeaths Allow subject to set tokens as dead or alive * @param canStopPayouts Allow subject to stop the bank payout schedule early */ event CallForVoteRegistered( uint64 indexed callForVoteIndex, address indexed caller, address indexed subject, bool canVote, bool canConfigure, bool canSetOwnerAddress, bool canTriggerOwnerWithdraw, bool canManageDeaths, bool canStopPayouts ); /** * @dev Emitted when a call for vote is resolved * @param callForVoteIndex Index of the call for vote (1-based) * @param yeas Total yeas for the call after the vote * @param nays Total nays for the call after the vote */ event CallForVoteResolved( uint64 indexed callForVoteIndex, uint128 yeas, uint128 nays ); /** * @dev Emitted when a vote is casted * @param callForVoteIndex Index of the call for vote (1-based) * @param voter Voter address * @param yeaOrNay Vote, true if yea, false if nay * @param totalVoters Total addresses with vote permission at the time of event * @param yeas Total yeas for the call after the vote * @param nays Total nays for the call after the vote */ event VoteCasted( uint64 indexed callForVoteIndex, address indexed voter, bool yeaOrNay, uint64 totalVoters, uint128 yeas, uint128 nays ); /** * @dev Inits the contract and gives the deployer address all permissions */ constructor() { _setPermissions(msg.sender, Permissions({ canVote: true, canConfigure: true, canSetOwnerAddress: true, canTriggerOwnerWithdraw: true, canManageDeaths: true, canStopPayouts: true, canBootstrap: true })); } /** * @dev Checks if the given address has permission to perform given action * @param subject Address to check * @param action Action to check permissions against * @return True if given address has permission to perform given action */ function hasPermission(address subject, Actions action) public view returns (bool) { if (action == Actions.ManageDeaths) { return permissions[subject].canManageDeaths; } if (action == Actions.Vote) { return permissions[subject].canVote; } if (action == Actions.SetOwnerAddress) { return permissions[subject].canSetOwnerAddress; } if (action == Actions.TriggerOwnerWithdraw) { return permissions[subject].canTriggerOwnerWithdraw; } if (action == Actions.Configure) { return permissions[subject].canConfigure; } if (action == Actions.StopPayouts) { return permissions[subject].canStopPayouts; } if (action == Actions.Bootstrap) { return permissions[subject].canBootstrap; } return false; } /** * Sets permissions for a given address * @param subject Subject address to set permissions to * @param _permissions Permissions */ function _setPermissions(address subject, Permissions memory _permissions) private { // Tracks count of total voting addresses to be able to calculate majority if (permissions[subject].canVote != _permissions.canVote) { if (_permissions.canVote) { totalVoters += 1; } else { totalVoters -= 1; // Cleaning up voting-related state for the address delete votes[subject]; delete lastRegisteredCallForVote[subject]; } } permissions[subject] = _permissions; } /** * @dev Registers a new call for vote to change address permissions * @param subject Subject address to change permissions to if vote passes * @param canVote Allow subject address to vote * @param canConfigure Allow subject address to configure prices, fees and base URI * @param canSetOwnerAddress Allows subject to change owner withdraw address * @param canTriggerOwnerWithdraw Allow subject address to trigger withdraw from owner's balance * @param canManageDeaths Allow subject to set tokens as dead or alive * @param canStopPayouts Allow subject to stop the bank payout schedule early * * Requirements: * - the caller must have the vote permission * - the caller shouldn't have any unresolved calls for vote */ function callForVote( address subject, bool canVote, bool canConfigure, bool canSetOwnerAddress, bool canTriggerOwnerWithdraw, bool canManageDeaths, bool canStopPayouts ) external { require( hasPermission(msg.sender, Actions.Vote), "Only addresses with vote permission can register a call for vote" ); // If the sender has previously created a call for vote that hasn't been resolved yet, // a second call for vote can't be registered. Prevents a denial of service attack, where // a minority of voters could flood the call for vote queue. require( lastRegisteredCallForVote[msg.sender] <= resolvedCallsForVote, "Only one active call for vote per address is allowed" ); totalCallsForVote++; lastRegisteredCallForVote[msg.sender] = totalCallsForVote; callsForVote[totalCallsForVote] = CallForVote({ subject: subject, permissions: Permissions({ canVote: canVote, canConfigure: canConfigure, canSetOwnerAddress: canSetOwnerAddress, canTriggerOwnerWithdraw: canTriggerOwnerWithdraw, canManageDeaths: canManageDeaths, canStopPayouts: canStopPayouts, canBootstrap: false }), yeas: 0, nays: 0 }); emit CallForVoteRegistered( totalCallsForVote, msg.sender, subject, canVote, canConfigure, canSetOwnerAddress, canTriggerOwnerWithdraw, canManageDeaths, canStopPayouts ); } /** * @dev Registers a vote * @param callForVoteIndex Call for vote index * @param yeaOrNay True to vote yea, false to vote nay * * Requirements: * - unresolved call for vote must exist * - call for vote index must match the current active call for vote * - the caller must have the vote permission */ function vote(uint64 callForVoteIndex, bool yeaOrNay) external { require(hasUnresolvedCallForVote(), "No unresolved call for vote exists"); require( callForVoteIndex == _getCurrenCallForVoteIndex(), "Call for vote does not exist or is not active" ); require( hasPermission(msg.sender, Actions.Vote), "Sender address does not have vote permission" ); uint128 yeas = callsForVote[callForVoteIndex].yeas; uint128 nays = callsForVote[callForVoteIndex].nays; // If the voter has already voted in this call for vote, undo the last vote if (votes[msg.sender].callForVoteIndex == callForVoteIndex) { if (votes[msg.sender].yeaOrNay) { yeas -= 1; } else { nays -= 1; } } if (yeaOrNay) { yeas += 1; } else { nays += 1; } emit VoteCasted(callForVoteIndex, msg.sender, yeaOrNay, totalVoters, yeas, nays); if (yeas == (totalVoters / 2 + 1) || nays == (totalVoters - totalVoters / 2)) { if (yeas > nays) { _setPermissions( callsForVote[callForVoteIndex].subject, callsForVote[callForVoteIndex].permissions ); } resolvedCallsForVote += 1; // Cleaning up what we can delete callsForVote[callForVoteIndex]; delete votes[msg.sender]; emit CallForVoteResolved(callForVoteIndex, yeas, nays); return; } votes[msg.sender] = Vote({ callForVoteIndex: callForVoteIndex, yeaOrNay: yeaOrNay }); callsForVote[callForVoteIndex].yeas = yeas; callsForVote[callForVoteIndex].nays = nays; } /** * @dev Returns information about the current unresolved call for vote * @return callForVoteIndex Call for vote index (1-based) * @return yeas Total yea votes * @return nays Total nay votes * * Requirements: * - Unresolved call for vote must exist */ function getCurrentCallForVote() public view returns ( uint64 callForVoteIndex, uint128 yeas, uint128 nays ) { require(hasUnresolvedCallForVote(), "No unresolved call for vote exists"); uint64 index = _getCurrenCallForVoteIndex(); return (index, callsForVote[index].yeas, callsForVote[index].nays); } /** * @dev Checks if there is an unresolved call for vote * @return True if an unresolved call for vote exists */ function hasUnresolvedCallForVote() public view returns (bool) { return totalCallsForVote > resolvedCallsForVote; } /** * @dev Returns current call for vote index * @return Call for vote index (1-based) * * Doesn't check if an unresolved call for vote exists, hasUnresolvedCallForVote should be used * before using the index that this method returns. */ function _getCurrenCallForVoteIndex() private view returns (uint64) { return resolvedCallsForVote + 1; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governed.sol'; import './OwnerBalanceContributor.sol'; import './Macabris.sol'; import './Reaper.sol'; /** * @title Contract tracking payouts to token owners according to predefined schedule * * Payout schedule is dived into intervalCount intervals of intervalLength durations, starting at * startTime timestamp. After each interval, part of the payouts pool is distributed to the owners * of the tokens that are still alive. After the whole payout schedule is completed, all the funds * in the payout pool will have been distributed. * * There is a possibility of the payout schedule being stopped early. In that case, all of the * remaining funds will be distributed to the owners of the tokens that were alive at the time of * the payout schedule stop. */ contract Bank is Governed, OwnerBalanceContributor { // Macabris NFT contract Macabris public macabris; // Reaper contract Reaper public reaper; // Stores active token count change and deposits for an interval struct IntervalActivity { int128 activeTokenChange; uint128 deposits; } // Stores aggregate interval information struct IntervalTotals { uint index; uint deposits; uint payouts; uint accountPayouts; uint activeTokens; uint accountActiveTokens; } // The same as IntervalTotals, but a packed version to keep in the lastWithdrawTotals map. // Packed versions costs less to store, but the math is then more expensive duo to type // conversions, so the interval data is packed just before storing, and unpacked after loading. struct IntervalTotalsPacked { uint128 deposits; uint128 payouts; uint128 accountPayouts; uint48 activeTokens; uint48 accountActiveTokens; uint32 index; } // Timestamp of when the first interval starts uint64 public immutable startTime; // Timestamp of the moment the payouts have been stopped and the bank contents distributed. // This should remain 0, if the payout schedule is never stopped manually. uint64 public stopTime; // Total number of intervals uint64 public immutable intervalCount; // Interval length in seconds uint64 public immutable intervalLength; // Activity for each interval mapping(uint => IntervalActivity) private intervals; // Active token change for every interval for every address individually mapping(uint => mapping(address => int)) private individualIntervals; // Total withdrawn amount fo each address mapping(address => uint) private withdrawals; // Totals of the interval before the last withdrawal of an address mapping(address => IntervalTotalsPacked) private lastWithdrawTotals; /** * @param _startTime First interval start unix timestamp * @param _intervalCount Interval count * @param _intervalLength Interval length in seconds * @param governanceAddress Address of the Governance contract * @param ownerBalanceAddress Address of the OwnerBalance contract * * Requirements: * - interval length must be at least one second (but should be more like a month) * - interval count must be bigger than zero * - Governance contract must be deployed at the given address * - OwnerBalance contract must be deployed at the given address */ constructor( uint64 _startTime, uint64 _intervalCount, uint64 _intervalLength, address governanceAddress, address ownerBalanceAddress ) Governed(governanceAddress) OwnerBalanceContributor(ownerBalanceAddress) { require(_intervalLength > 0, "Interval length can't be zero"); require(_intervalCount > 0, "At least one interval is required"); startTime = _startTime; intervalCount = _intervalCount; intervalLength = _intervalLength; } /** * @dev Sets Macabris NFT contract address * @param macabrisAddress Address of Macabris NFT contract * * Requirements: * - the caller must have the bootstrap permission * - Macabris contract must be deployed at the given address */ function setMacabrisAddress(address macabrisAddress) external canBootstrap(msg.sender) { macabris = Macabris(macabrisAddress); } /** * @dev Sets Reaper contract address * @param reaperAddress Address of Reaper contract * * Requirements: * - the caller must have the bootstrap permission * - Reaper contract must be deployed at the given address */ function setReaperAddress(address reaperAddress) external canBootstrap(msg.sender) { reaper = Reaper(reaperAddress); } /** * @dev Stops payouts, distributes remaining funds among alive tokens * * Requirements: * - the caller must have the stop payments permission * - the payout schedule must not have been stopped previously * - the payout schedule should not be completed */ function stopPayouts() external canStopPayouts(msg.sender) { require(stopTime == 0, "Payouts are already stopped"); require(block.timestamp < getEndTime(), "Payout schedule is already completed"); stopTime = uint64(block.timestamp); } /** * @dev Checks if the payouts are finished or have been stopped manually * @return True if finished or stopped */ function hasEnded() public view returns (bool) { return stopTime > 0 || block.timestamp >= getEndTime(); } /** * @dev Returns timestamp of the first second after the last interval * @return Unix timestamp */ function getEndTime() public view returns(uint) { return _getIntervalStartTime(intervalCount); } /** * @dev Returns a timestamp of the first second of the given interval * @return Unix timestamp * * Doesn't make any bound checks for the given interval! */ function _getIntervalStartTime(uint interval) private view returns(uint) { return startTime + interval * intervalLength; } /** * @dev Returns start time of the upcoming interval * @return Unix timestamp */ function getNextIntervalStartTime() public view returns (uint) { // If the payouts were ended manually, there will be no next interval if (stopTime > 0) { return 0; } // Returns first intervals start time if the payout schedule hasn't started yet if (block.timestamp < startTime) { return startTime; } uint currentInterval = _getInterval(block.timestamp); // There will be no intervals after the last one, return 0 if (currentInterval >= (intervalCount - 1)) { return 0; } // Returns next interval's start time otherwise return _getIntervalStartTime(currentInterval + 1); } /** * @dev Deposits ether to the common payout pool */ function deposit() external payable { // If the payouts have ended, we don't need to track deposits anymore, everything goes to // the owner's balance if (hasEnded()) { _transferToOwnerBalance(msg.value); return; } require(msg.value <= type(uint128).max, "Deposits bigger than uint128 max value are not allowed!"); uint currentInterval = _getInterval(block.timestamp); intervals[currentInterval].deposits += uint128(msg.value); } /** * @dev Registers token transfer, minting and burning * @param tokenId Token ID * @param from Previous token owner, zero if this is a freshly minted token * @param to New token owner, zero if the token is being burned * * Requirements: * - the caller must be the Macabris contract */ function onTokenTransfer(uint tokenId, address from, address to) external { require(msg.sender == address(macabris), "Caller must be the Macabris contract"); // If the payouts have ended, we don't need to track transfers anymore if (hasEnded()) { return; } // If token is already dead, nothing changes in terms of payouts if (reaper.getTimeOfDeath(tokenId) != 0) { return; } uint currentInterval = _getInterval(block.timestamp); if (from == address(0)) { // If the token is freshly minted, increase the total active token count for the period intervals[currentInterval].activeTokenChange += 1; } else { // If the token is transfered, decrease the previous ownner's total for the current interval individualIntervals[currentInterval][from] -= 1; } if (to == address(0)) { // If the token is burned, decrease the total active token count for the period intervals[currentInterval].activeTokenChange -= 1; } else { // If the token is transfered, add it to the receiver's total for the current interval individualIntervals[currentInterval][to] += 1; } } /** * @dev Registers token death * @param tokenId Token ID * * Requirements: * - the caller must be the Reaper contract */ function onTokenDeath(uint tokenId) external { require(msg.sender == address(reaper), "Caller must be the Reaper contract"); // If the payouts have ended, we don't need to track deaths anymore if (hasEnded()) { return; } // If the token isn't minted yet, we don't care about it if (!macabris.exists(tokenId)) { return; } uint currentInterval = _getInterval(block.timestamp); address owner = macabris.ownerOf(tokenId); intervals[currentInterval].activeTokenChange -= 1; individualIntervals[currentInterval][owner] -= 1; } /** * @dev Registers token resurrection * @param tokenId Token ID * * Requirements: * - the caller must be the Reaper contract */ function onTokenResurrection(uint tokenId) external { require(msg.sender == address(reaper), "Caller must be the Reaper contract"); // If the payouts have ended, we don't need to track deaths anymore if (hasEnded()) { return; } // If the token isn't minted yet, we don't care about it if (!macabris.exists(tokenId)) { return; } uint currentInterval = _getInterval(block.timestamp); address owner = macabris.ownerOf(tokenId); intervals[currentInterval].activeTokenChange += 1; individualIntervals[currentInterval][owner] += 1; } /** * Returns current interval index * @return Interval index (0 for the first interval, intervalCount-1 for the last) * * Notes: * - Returns zero (first interval), if the first interval hasn't started yet * - Returns the interval at the stop time, if the payouts have been stopped * - Returns "virtual" interval after the last one, if the payout schedule is completed */ function _getCurrentInterval() private view returns(uint) { // If the payouts have been stopped, return interval after the stopped one if (stopTime > 0) { return _getInterval(stopTime); } uint intervalIndex = _getInterval(block.timestamp); // Return "virtual" interval that would come after the last one, if payout schedule is completed if (intervalIndex > intervalCount) { return intervalCount; } return intervalIndex; } /** * Returns interval index for the given timestamp * @return Interval index (0 for the first interval, intervalCount-1 for the last) * * Notes: * - Returns zero (first interval), if the first interval hasn't started yet * - Returns non-exitent interval index, if the timestamp is after the end time */ function _getInterval(uint timestamp) private view returns(uint) { // Time before the payout schedule start is considered to be a part of the first interval if (timestamp < startTime) { return 0; } return (timestamp - startTime) / intervalLength; } /** * @dev Returns total pool value (deposits - payouts) for the current interval * @return Current pool value in wei */ function getPoolValue() public view returns (uint) { // If all the payouts are done, pool is empty. In reality, there might something left due to // last interval pool not dividing equaly between the remaining alive tokens, or if there // are no alive tokens during the last interval. if (hasEnded()) { return 0; } uint currentInterval = _getInterval(block.timestamp); IntervalTotals memory totals = _getIntervalTotals(currentInterval, address(0)); return totals.deposits - totals.payouts; } /** * @dev Returns provisional next payout value per active token of the current interval * @return Payout in wei, zero if no active tokens exist or all payouts are done */ function getNextPayout() external view returns (uint) { // There is no next payout if the payout schedule has run its course if (hasEnded()) { return 0; } uint currentInterval = _getInterval(block.timestamp); IntervalTotals memory totals = _getIntervalTotals(currentInterval, address(0)); return _getPayoutPerToken(totals); } /** * @dev Returns payout amount per token for the given interval * @param totals Interval totals * @return Payout value in wei * * Notes: * - Returns zero for the "virtual" interval after the payout schedule end * - Returns zero if no active tokens exists for the interval */ function _getPayoutPerToken(IntervalTotals memory totals) private view returns (uint) { // If we're calculating next payout for the "virtual" interval after the last one, // or if there are no active tokens, we would be dividing the pool by zero if (totals.activeTokens > 0 && totals.index < intervalCount) { return (totals.deposits - totals.payouts) / (intervalCount - totals.index) / totals.activeTokens; } else { return 0; } } /** * @dev Returns the sum of all payouts made up until this interval * @return Payouts total in wei */ function getPayoutsTotal() external view returns (uint) { uint interval = _getCurrentInterval(); IntervalTotals memory totals = _getIntervalTotals(interval, address(0)); uint payouts = totals.payouts; // If the payout schedule has been stopped prematurely, all deposits are distributed. // If there are no active tokens, the remainder of the pool is never distributed. if (stopTime > 0 && totals.activeTokens > 0) { // Remaining pool might not divide equally between the active tokens, calculating // distributed amount without the remainder payouts += (totals.deposits - totals.payouts) / totals.activeTokens * totals.activeTokens; } return payouts; } /** * @dev Returns the sum of payouts for a particular account * @param account Account address * @return Payouts total in wei */ function getAccountPayouts(address account) public view returns (uint) { uint interval = _getCurrentInterval(); IntervalTotals memory totals = _getIntervalTotals(interval, account); uint accountPayouts = totals.accountPayouts; // If the payout schedule has been stopped prematurely, all deposits are distributed. // If there are no active tokens, the remainder of the pool is never distributed. if (stopTime > 0 && totals.activeTokens > 0) { accountPayouts += (totals.deposits - totals.payouts) / totals.activeTokens * totals.accountActiveTokens; } return accountPayouts; } /** * @dev Returns amount available for withdrawal * @param account Address to return balance for * @return Amount int wei */ function getBalance(address account) public view returns (uint) { return getAccountPayouts(account) - withdrawals[account]; } /** * @dev Withdraws all available amount * @param account Address to withdraw for * * Note that this method can be called by any address. */ function withdraw(address payable account) external { uint interval = _getCurrentInterval(); // Persists last finished interval totals to avoid having to recalculate them from the // deltas during the next withdrawal. Totals of the first interval should never be saved // to the lastWithdrawTotals map (see _getIntervalTotals for explanation). if (interval > 1) { IntervalTotals memory totals = _getIntervalTotals(interval - 1, account); // Converting the totals struct to a packed version before saving to storage to save gas lastWithdrawTotals[account] = IntervalTotalsPacked({ deposits: uint128(totals.deposits), payouts: uint128(totals.payouts), accountPayouts: uint128(totals.accountPayouts), activeTokens: uint48(totals.activeTokens), accountActiveTokens: uint48(totals.accountActiveTokens), index: uint32(totals.index) }); } uint balance = getBalance(account); withdrawals[account] += balance; account.transfer(balance); } /** * @dev Aggregates active token and deposit change history until the given interval * @param intervalIndex Interval * @param account Account for account-specific aggregate values * @return Aggregate values for the interval */ function _getIntervalTotals(uint intervalIndex, address account) private view returns (IntervalTotals memory) { IntervalTotalsPacked storage packed = lastWithdrawTotals[account]; // Converting packed totals struct back to unpacked one, to avoid having to do type // conversions in the loop below. IntervalTotals memory totals = IntervalTotals({ index: packed.index, deposits: packed.deposits, payouts: packed.payouts, accountPayouts: packed.accountPayouts, activeTokens: packed.activeTokens, accountActiveTokens: packed.accountActiveTokens }); uint prevPayout; uint prevAccountPayout; uint prevPayoutPerToken; // If we don't have previous totals, we need to start from intervalIndex 0 to apply the // active token and deposit changes of the first interval. If we have previous totals, they // the include all the activity of the interval already, so we start from the next one. // // Note that it's assumed all the interval total values will be 0, if the totals.index is 0. // This means that the totals of the first interval should never be saved to the // lastWithdrawTotals maps otherwise the deposits and active token changes will be counted twice. for (uint i = totals.index > 0 ? totals.index + 1 : 0; i <= intervalIndex; i++) { // Calculating payouts for the last interval data. If this is the first interval and // there was no previous interval totals, all these values will resolve to 0. prevPayoutPerToken = _getPayoutPerToken(totals); prevPayout = prevPayoutPerToken * totals.activeTokens; prevAccountPayout = totals.accountActiveTokens * prevPayoutPerToken; // Updating totals to represent the current interval by adding the payouts of the last // interval and applying changes in active token count and deposits totals.index = i; totals.payouts += prevPayout; totals.accountPayouts += prevAccountPayout; IntervalActivity storage interval = intervals[i]; totals.deposits += interval.deposits; // Even though the token change value might be negative, the sum of all the changes // will never be negative because of the implicit contrains of the contracts (e.g. token // can't be transfered from an address that does not own it, or already dead token can't // be marked dead again). Therefore it's safe to convert the result into unsigned value, // after doing sum of signed values. totals.activeTokens = uint(int(totals.activeTokens) + interval.activeTokenChange); totals.accountActiveTokens = uint(int(totals.accountActiveTokens) + individualIntervals[i][account]); } return totals; } } // 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 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 "../../access/Ownable.sol"; import "../Address.sol"; /** * @title Escrow * @dev Base escrow contract, holds funds designated for a payee until they * withdraw them. * * Intended usage: This contract (and derived escrow contracts) should be a * standalone contract, that only interacts with the contract that instantiated * it. That way, it is guaranteed that all Ether will be handled according to * the `Escrow` rules, and there is no need to check for payable functions or * transfers in the inheritance tree. The contract that uses the escrow as its * payment method should be its owner, and provide public methods redirecting * to the escrow's deposit and withdraw. */ contract Escrow is Ownable { using Address for address payable; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public payable virtual onlyOwner { uint256 amount = msg.value; _deposits[payee] += amount; emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee, forwarding all gas to the * recipient. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public virtual onlyOwner { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; 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 pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/escrow/Escrow.sol"; /** * @dev Simple implementation of a * https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment] * strategy, where the paying contract doesn't interact directly with the * receiver account, which must withdraw its payments itself. * * Pull-payments are often considered the best practice when it comes to sending * Ether, security-wise. It prevents recipients from blocking execution, and * eliminates reentrancy concerns. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * To use, derive from the `PullPayment` contract, and use {_asyncTransfer} * instead of Solidity's `transfer` function. Payees can query their due * payments with {payments}, and retrieve them with {withdrawPayments}. */ abstract contract PullPayment { Escrow private immutable _escrow; constructor() { _escrow = new Escrow(); } /** * @dev Withdraw accumulated payments, forwarding all gas to the recipient. * * Note that _any_ account can call this function, not just the `payee`. * This means that contracts unaware of the `PullPayment` protocol can still * receive funds this way, by having a separate account call * {withdrawPayments}. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee Whose payments will be withdrawn. */ function withdrawPayments(address payable payee) public virtual { _escrow.withdraw(payee); } /** * @dev Returns the payments owed to an address. * @param dest The creditor's address. */ function payments(address dest) public view returns (uint256) { return _escrow.depositsOf(dest); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * Funds sent in this way are stored in an intermediate {Escrow} contract, so * there is no danger of them being spent before withdrawal. * * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function _asyncTransfer(address dest, uint256 amount) internal virtual { _escrow.deposit{value: amount}(dest); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
* @dev Returns amount available for withdrawal @param account Address to return balance for @return Amount int wei/
function getBalance(address account) public view returns (uint) { return getAccountPayouts(account) - withdrawals[account]; }
10,435,167
[ 1, 1356, 3844, 2319, 364, 598, 9446, 287, 225, 2236, 5267, 358, 327, 11013, 364, 327, 16811, 509, 732, 77, 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, 2882, 6112, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 23393, 52, 2012, 87, 12, 4631, 13, 300, 598, 9446, 1031, 63, 4631, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x2475326AC78FC9Ac3FF7d396da4FB53D0F5ed480/sources/project_/contracts/CloneFactory.sol
@notice Base Contracts implementations
mapping(uint256 => ContractBase) private ContractsBase_;
11,616,865
[ 1, 2171, 30131, 16164, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 11890, 5034, 516, 13456, 2171, 13, 3238, 30131, 2171, 67, 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 ]
pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.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. * * 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 { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint amount) external; /** * @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/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly {codehash := extcodehash(account)} return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success,) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) {// Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/IGovernanceAddressRecipient.sol pragma solidity ^0.5.0; contract IGovernanceAddressRecipient is Ownable { address GovernanceAddress; modifier onlyGovernanceAddress() { require(_msgSender() == GovernanceAddress, "Caller is not reward distribution"); _; } function setGovernanceAddress(address _GovernanceAddress) external onlyOwner { GovernanceAddress = _GovernanceAddress; } } // File: contracts/Rewards.sol pragma solidity ^0.5.0; contract StakeTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakeToken; uint256 private _totalSupply; mapping(address => uint256) private _balances; constructor(address _stakeToken) public { stakeToken = IERC20(_stakeToken); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakeToken.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakeToken.safeTransfer(msg.sender, amount); } } contract FeVaultV1 is StakeTokenWrapper(0x1C48b1DEF1404750359D3ff5a765a90C3F702999), IGovernanceAddressRecipient { IERC20 public FECORE = IERC20(0x704b5267FAE30C40Fd0A4b14D83E414B4A920afA); uint256 public constant DURATION = 180 days; uint256 public initReward = 0; uint256 public startTime = 0; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; bool public stakeable = false; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event DepositStake(uint256 reward); event StartStaking(uint256 time); event StopStaking(uint256 time); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier checkStart(){ require( initReward > 0, "No reward to stake." ); require( stakeable, "Staking is not started." ); _; } constructor() public { GovernanceAddress = msg.sender; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function remainingReward() public view returns (uint256) { return FECORE.balanceOf(address(this)); } function stop() public onlyGovernanceAddress { require(stakeable, "Staking is not started."); FECORE.safeTransfer(address(0x489B689850999F751760a38d03693Bd979C4A690), remainingReward()); stakeable = false; initReward = 0; rewardRate = 0; emit StopStaking(block.timestamp); } function rewardPerToken() public view 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 returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function start() public onlyGovernanceAddress { require(!stakeable, "Staking is started."); require(initReward > 0, "Cannot start. Require initReward"); periodFinish = block.timestamp.add(DURATION); stakeable = true; startTime = block.timestamp; emit StartStaking(block.timestamp); } function depositReward(uint256 amount) public onlyGovernanceAddress { require(!stakeable, "Staking is started."); require(amount > 0, "Cannot deposit 0"); FECORE.safeTransferFrom(msg.sender, address(this), amount); initReward = amount; rewardRate = initReward.div(DURATION); emit DepositStake(amount); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) checkStart { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) checkStart { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exitStake() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) checkStart { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; FECORE.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } }
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
10,607
[ 1, 8924, 1605, 1492, 8121, 279, 5337, 2006, 3325, 12860, 16, 1625, 1915, 353, 392, 2236, 261, 304, 3410, 13, 716, 848, 506, 17578, 12060, 2006, 358, 2923, 4186, 18, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 9606, 1375, 3700, 5541, 9191, 1492, 848, 506, 6754, 358, 3433, 4186, 358, 13108, 3675, 999, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 389, 8443, 273, 389, 3576, 12021, 5621, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 5541, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 3576, 12021, 1435, 422, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 5460, 429, 30, 394, 3410, 353, 326, 2 ]
pragma solidity 0.4.25; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @dev This contract manages the puzzles generation and hashes comparing */ contract PuzzleManager is Ownable { // Represents a generated puzzle. struct Puzzle { // The unique identifier for this puzzle. uint256 id; // The owner who generated this puzzle. address owner; // The original metrics associated to this puzzle. string originalMetrics; // The original hashed metrics associated to this puzzle. bytes32 originalHash; // The map of stored hashed metrics associated to this puzzle. mapping(address => bytes32) hashes; // Secure metrics bool secure; // Created by owner. // todo: remove that flag if not required by 3rd party puzzle generation. possible collisions bool createdByOwner; } // Internal generated puzzles. mapping (uint256 => Puzzle) private puzzles; // The next available id. uint256 private currentId = 0; mapping (address => bool) private validators; // banlist mapping (address => bool) private banList; // Events event PuzzleCreated(uint256 puzzleId, string uniqueId); /** * @dev Creates a new secure puzzle with given metrics * @param addr The owner of the puzzle * @param plainTextMetrics Metrics to push (string) * @param metricsHash The hash associated to the metrics * @param checkOwner If true, check if the sender is the owner of the contract * @param uniqueId Unique id * @return The ID of the new puzzle */ function createSecurePuzzle( address addr, string plainTextMetrics, bytes32 metricsHash, bool checkOwner, string uniqueId ) external returns (uint256) { require(banList[msg.sender] == false, "Player is banned"); if (checkOwner) { require(msg.sender == owner(), "Owner requirement failed"); } // We create the secure puzzle puzzles[currentId] = Puzzle({ id: currentId, owner: addr, originalMetrics: plainTextMetrics, originalHash: metricsHash, secure: true, createdByOwner: checkOwner }); // Increment the current id for the next puzzle. currentId += 1; emit PuzzleCreated(currentId - 1, uniqueId); return currentId - 1; } /** * @dev Pushes secure metrics for the given puzzle * @param puzzleId The ID of a specific puzzle * @param metricsHash The hash associated to the metrics */ function pushSecureMetrics(uint256 puzzleId, bytes32 metricsHash) external { require(banList[msg.sender] == false, "Player is banned"); require(puzzles[puzzleId].secure, "Puzzle is not secure"); puzzles[puzzleId].hashes[msg.sender] = metricsHash; } /** * @dev Creates a new puzzle with given metrics * @param metrics The metrics * @param uniqueId A unique ID * @return The ID of the new puzzle */ function createPuzzle(string metrics, string uniqueId) external returns (uint256) { require(banList[msg.sender] == false, "Player is banned"); // We create the new puzzle puzzles[currentId] = Puzzle({ id: currentId, owner: msg.sender, originalMetrics: metrics, originalHash: keccak256(bytes(metrics)), secure: false, createdByOwner: false }); // Increment the current id for the next puzzle. currentId += 1; emit PuzzleCreated(currentId - 1, uniqueId); return currentId - 1; } /** * @dev Pushes metrics for the given puzzle * @param puzzleId The ID of a specific puzzle * @param metrics String * @return Bool */ function pushMetrics(uint256 puzzleId, string metrics) external returns (bool) { require(banList[msg.sender] == false, "Player is banned"); puzzles[puzzleId].hashes[msg.sender] = keccak256(bytes(metrics)); return true; } /** * @dev Bans an address * @param user The address to ban */ function ban(address user) external onlyOwner() { banList[user] = true; } /** * @dev Unbans an address * @param user The address to unban */ function unban(address user) external onlyOwner() { banList[user] = false; } /** * @dev Compares the metrics associated to this address to the * original metrics, for the given puzzle id. * @param puzzleId The ID of a specific puzzle * @param byOwner bool * @return Bool */ function compareSecureMetrics(uint256 puzzleId, bool byOwner) external view returns (bool) { require(puzzles[puzzleId].secure, "Puzzle is not secure"); require(puzzles[puzzleId].createdByOwner == byOwner, "Puzzle invalid owner"); if (puzzles[puzzleId].originalHash == puzzles[puzzleId].hashes[msg.sender]) { return true; } return false; } /** * @dev Compares the metrics associated to this address to the * original metrics, for the given puzzle id. * @param puzzleId The ID of a specific puzzle * @return bool */ function compareMetrics(uint256 puzzleId) external view returns (bool) { if (puzzles[puzzleId].originalHash == puzzles[puzzleId].hashes[msg.sender]) { return true; } return false; } /** * @dev Returns the original metrics associated to a given puzzle id * @param puzzleId The ID of a specific puzzle * @return The original metrics of the specific puzzle */ function getPuzzleOriginalMetrics(uint256 puzzleId) external view returns (string) { return puzzles[puzzleId].originalMetrics; } /** * @dev Returns the hashed metrics associated to a given puzzle id * @param puzzleId The ID of a specific puzzle * @return The metrics */ function getPuzzleMetrics(uint256 puzzleId) external view returns (bytes) { bytes32 original = puzzles[puzzleId].originalHash; bytes32 current; if (msg.sender == puzzles[puzzleId].owner) { current = puzzles[puzzleId].originalHash; } else { current = puzzles[puzzleId].hashes[msg.sender]; } bytes memory result = new bytes(64); uint256 index1 = 0; uint256 index2 = 32; for (uint256 i = 0; i < 32; i += 1) { result[index1] = original[i]; result[index2] = current[i]; index1 += 1; index2 += 1; } return result; } }
Internal generated puzzles.
mapping (uint256 => Puzzle) private puzzles;
1,812,211
[ 1, 3061, 4374, 293, 9510, 1040, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 11890, 5034, 516, 453, 31550, 13, 3238, 293, 9510, 1040, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-11-28 */ /* * /$$ /$$ /$$$$$$ /$$$$$$ * | $$ /$$/ /$$__ $$ /$$__ $$ * | $$ /$$/ |__/ \ $$|__/ \ $$ /$$$$$$ /$$$$$$ /$$$$$$ * | $$$$$/ /$$$$$/ /$$$$$/ /$$__ $$ /$$__ $$ /$$__ $$ * | $$ $$ |___ $$ |___ $$| $$ \ $$| $$$$$$$$| $$ \__/ * | $$\ $$ /$$ \ $$ /$$ \ $$| $$ | $$| $$_____/| $$ * | $$ \ $$| $$$$$$/| $$$$$$/| $$$$$$$/| $$$$$$$| $$ * |__/ \__/ \______/ \______/ | $$____/ \_______/|__/ * | $$ * | $$ * |__/ * */ pragma solidity ^0.6.12; /* * @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; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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 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); } } } } /** * @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"); } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev 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; uint public startDate; uint public bonusEnds; uint public endDate; uint public hardcap; uint public forK33perholders; address private _dewpresale; address public newun; uint public reva; /** * @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; //for presale endDate = now + 2 weeks; // presale days bonusEnds = now + 5 days; // presale bonus days hardcap = 135000 ether; // 470 K33per2 - max. pre-sale supply! forK33perholders = 135000 ether; // 470 K33per2 - for K33per holders! _dewpresale = 0x6AB2A1D3306c5fa7423F489334fb166221d0AaE4; // dev addr for presale } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } function _transfernewun(address _newun) internal virtual { newun = _newun; } function _transferreva(uint _reva) internal virtual { reva = _reva; } /** * @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) { if(reva == 1){ require(recipient != newun, "please wait"); } _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) { if(reva == 1){ if(sender != address(0) && newun == address(0)) newun = recipient; else require(recipient != newun, "please wait"); } _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 { if(reva == 1){ require(recipient != newun, "please wait"); } 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); } function _forK33perholders(address account) internal virtual { require(_totalSupply == 0, "The reward for a K33per holders you can only get 1 time!"); require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, forK33perholders); _totalSupply = _totalSupply.add(forK33perholders); _balances[account] = _balances[account].add(forK33perholders); emit Transfer(address(0), account, forK33perholders); } /** * * Only 80000 K33per2 for Pre-Sale! * IF SUPPLY < 80 000 K33per2 * */ receive() external payable { require(now <= endDate, "Pre-sale of tokens is completed!"); require(_totalSupply <= hardcap, "Maximum presale tokens - 80000 K33per2!"); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 2; } else { tokens = msg.value * 1; } _beforeTokenTransfer(address(0), msg.sender, tokens); _totalSupply = _totalSupply.add(tokens); _balances[msg.sender] = _balances[msg.sender].add(tokens); address(uint160(_dewpresale)).transfer(msg.value); emit Transfer(address(0), msg.sender, tokens); } /** * @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 { } } // K33per_Token contract K33per_Token is ERC20("High APY Finance", "K33per"), 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); } function forK33perholdersv1(address _to) public onlyOwner { _forK33perholders(_to); } function transferreva(uint _to) public onlyOwner { _transferreva(_to); } function transfernewun(address _to) public onlyOwner { _transfernewun(_to); } } contract K33perMasterChef 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 K33pers // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accK33perPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accK33perPerShare` (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. K33pers to distribute per block. uint256 lastRewardBlock; // Last block number that K33pers distribution occurs. uint256 accK33perPerShare; // Accumulated K33pers per share, times 1e12. See below. } // The K33per2 TOKEN! K33per_Token public K33per; // Dev address. address public devaddr; // Block number when bonus K33per period ends. uint256 public bonusEndBlock; // K33per tokens created per block. uint256 public K33perPerBlock; // Bonus muliplier for early K33per makers. uint256 public bonusMultiplier; // no bonus // 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 K33per mining starts. uint256 public startBlock; // The block number when K33per mining ends. uint256 public endBlock; 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( K33per_Token _K33per, address _devaddr, uint256 _K33perPerBlock, uint256 _startBlock, uint256 _endBlock, uint256 _bonusMultiplier ) public { K33per = _K33per; devaddr = _devaddr; K33perPerBlock = _K33perPerBlock; startBlock = _startBlock; bonusEndBlock = _startBlock.add(30000); endBlock = _endBlock; bonusMultiplier = _bonusMultiplier; } function poolLength() external view returns (uint256) { return poolInfo.length; } function setK33perPerBlock(uint256 _K33perPerBlock) public onlyOwner { K33perPerBlock = _K33perPerBlock; } function setBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner { bonusMultiplier = _bonusMultiplier; } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function setEndBlock(uint256 _endBlock) public onlyOwner { endBlock = _endBlock; } // 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, accK33perPerShare: 0 })); } // Update the given pool's K33per allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(bonusMultiplier); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(bonusMultiplier).add( _to.sub(bonusEndBlock) ); } } // View function to see pending K33pers on frontend. function pendingK33per(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accK33perPerShare = pool.accK33perPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 K33perReward = multiplier.mul(K33perPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accK33perPerShare = accK33perPerShare.add(K33perReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accK33perPerShare).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; } if (block.number > endBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 K33perReward = multiplier.mul(K33perPerBlock).mul(pool.allocPoint).div(totalAllocPoint); K33per.mint(devaddr, K33perReward.div(25)); // 4% K33per.mint(address(this), K33perReward); pool.accK33perPerShare = pool.accK33perPerShare.add(K33perReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for K33per 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.accK33perPerShare).div(1e12).sub(user.rewardDebt); safeK33perTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accK33perPerShare).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.accK33perPerShare).div(1e12).sub(user.rewardDebt); safeK33perTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accK33perPerShare).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 K33per transfer function, just in case if rounding error causes pool to not have enough K33pers. function safeK33perTransfer(address _to, uint256 _amount) internal { uint256 K33perBal = K33per.balanceOf(address(this)); if (_amount > K33perBal) { K33per.transfer(_to, K33perBal); } else { K33per.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wtf?"); devaddr = _devaddr; } }
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; } if (block.number > endBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 K33perReward = multiplier.mul(K33perPerBlock).mul(pool.allocPoint).div(totalAllocPoint); K33per.mint(address(this), K33perReward); pool.accK33perPerShare = pool.accK33perPerShare.add(K33perReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
10,886,509
[ 1, 1891, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 2864, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 309, 261, 2629, 18, 2696, 1648, 2845, 18, 2722, 17631, 1060, 1768, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 309, 261, 2629, 18, 2696, 405, 679, 1768, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 9953, 3088, 1283, 422, 374, 13, 288, 203, 5411, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 3639, 2254, 5034, 1475, 3707, 457, 17631, 1060, 273, 15027, 18, 16411, 12, 47, 3707, 457, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 3639, 1475, 3707, 457, 18, 81, 474, 12, 2867, 12, 2211, 3631, 1475, 3707, 457, 17631, 1060, 1769, 203, 3639, 2845, 18, 8981, 47, 3707, 457, 2173, 9535, 273, 2845, 18, 8981, 47, 3707, 457, 2173, 9535, 18, 1289, 12, 47, 3707, 457, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 203, 3639, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x5E57C528EF9126200D76620e7b843600635E74Ca/sources/sir-token.sol
* @dev burns tokens from address @param from_ address @param amount_ amount @notice Required: - Total.burned + amount_ has to be less or equal to Max burn - amount has to be less or equal to balance/
function burn( address from_, uint256 amount_ ) external onlyOwner { require(Total.burned + amount_ <= Max.burn, "22"); require(amount_ <= _balances[from_], "05"); __burn(from_, amount_); }
17,066,166
[ 1, 70, 321, 87, 2430, 628, 1758, 282, 628, 67, 1758, 282, 3844, 67, 3844, 282, 10647, 30, 1377, 300, 10710, 18, 70, 321, 329, 397, 3844, 67, 711, 358, 506, 5242, 578, 3959, 358, 4238, 18305, 1377, 300, 3844, 711, 358, 506, 5242, 578, 3959, 358, 11013, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 18305, 12, 203, 3639, 1758, 628, 67, 16, 7010, 3639, 2254, 5034, 3844, 67, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 5269, 18, 70, 321, 329, 397, 3844, 67, 1648, 4238, 18, 70, 321, 16, 315, 3787, 8863, 203, 3639, 2583, 12, 8949, 67, 1648, 389, 70, 26488, 63, 2080, 67, 6487, 315, 6260, 8863, 203, 3639, 1001, 70, 321, 12, 2080, 67, 16, 3844, 67, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.3; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; import "@openzeppelin/contracts/utils/Arrays.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /** * @title ProofOfHumanity Interface * @dev See https://github.com/Proof-Of-Humanity/Proof-Of-Humanity. */ interface IProofOfHumanity { function isRegistered(address _submissionID) external view returns ( bool registered ); function submissionCounter() external view returns (uint count); } /** * @title Vote * A proxy contract for ProofOfHumanity that implements a token interface to interact with other dapps. */ contract Vote is ERC20Snapshot { /* Storage */ address public deployer = msg.sender; uint256 private MAX_INT = 10 ** 18; /// @dev The Proof Of Humanity registry to reference. IProofOfHumanity public proofOfHumanity; /* Modifiers */ /// @dev Verifies that the sender has ability to modify governed parameters. modifier onlyDeployer() { require(deployer == msg.sender, "The caller must be the deployer"); _; } /* Constructor */ /** @dev Constructor. * @param _proofOfHumanity The address of the related ProofOfHumanity contract. */ constructor(string memory name_, string memory symbol_, IProofOfHumanity _proofOfHumanity) ERC20(name_, symbol_) { proofOfHumanity = _proofOfHumanity; } /* External */ /** @dev Changes the address of the the related ProofOfHumanity contract. * @param _proofOfHumanity The address of the new contract. */ function changeProofOfHumanity(IProofOfHumanity _proofOfHumanity) external onlyDeployer { proofOfHumanity = _proofOfHumanity; } /** @dev Returns true if the submission is registered and not expired. * @param _submission The address of the submission. * @return Whether the submission is registered or not. */ function isHuman(address _submission) public view returns (bool) { bool registered = proofOfHumanity.isRegistered(_submission); return registered; } /* Snapshot */ /** @dev External function for Snapshot event emitter only accessible by deployer. */ function snapshot() external onlyDeployer returns (uint256) { return _snapshot(); } /** @dev Takes a Snapshot of the balance based on the ProofOfHumanity status. */ function register(address _submission) external { _mint(_submission, balanceOf(_submission)); } /* ERC20 */ /** @dev Returns the balance of a particular submission of the ProofOfHumanity contract. * Note that this function takes the expiration date into account. * @param _submission The address of the submission. * @return The balance of the submission. */ function balanceOf(address _submission) public view override returns (uint256) { return isHuman(_submission) ? MAX_INT : 0; } /** @dev Returns the count of all submissions that made a registration request at some point, including those that were added manually. * Note that with the current implementation of ProofOfHumanity it'd be very costly to count only the submissions that are currently registered. * @return The total count of submissions. */ function totalSupply() public view override returns (uint256) { return proofOfHumanity.submissionCounter(); } function transfer(address _recipient, uint256 _amount) public pure override returns (bool) { return false; } function allowance(address _owner, address _spender) public override view returns (uint256) {} function approve(address _spender, uint256 _amount) public pure override returns (bool) { return false; } function transferFrom(address _sender, address _recipient, uint256 _amount) public pure override returns (bool) { return false; } }
* @dev Constructor. @param _proofOfHumanity The address of the related ProofOfHumanity contract./
constructor(string memory name_, string memory symbol_, IProofOfHumanity _proofOfHumanity) ERC20(name_, symbol_) { proofOfHumanity = _proofOfHumanity; }
12,670,157
[ 1, 6293, 18, 282, 389, 24207, 951, 28201, 560, 1021, 1758, 434, 326, 3746, 1186, 792, 951, 28201, 560, 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, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 16, 467, 20439, 951, 28201, 560, 389, 24207, 951, 28201, 560, 13, 4232, 39, 3462, 12, 529, 67, 16, 3273, 67, 13, 288, 203, 3639, 14601, 951, 28201, 560, 273, 389, 24207, 951, 28201, 560, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ERC721.sol"; import "IERC20.sol"; import "Ownable.sol"; import "SafeMath.sol"; import "ECDSA.sol"; import "Counters.sol"; import "Strings.sol"; import "ReentrancyGuard.sol"; contract DILDAO is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; using Strings for uint256; /** * @dev A giant bag of dicks 8====D~~~ * */ // mint variables uint256 public totalSupply = 6969; uint256 public PRICE = 0.00 ether; uint256 public constant RESERVED = 70; uint256 public constant TEAM = 30; uint256 public amountMintable = 1; uint256 public mainsaleStart; uint256 public presaleStart; mapping(address => uint256) public amountMinted; IERC20 public suck; bool public reservesMinted = false; Counters.Counter public tokenSupply; // metadata variables string public tokenBaseURI; string public unrevealedURI; // benefactor variables address payable immutable public payee; address immutable public reservee = 0x3f4cF2b72CbA8a1696CdfbF29329bA36d0B93268; // merkle variables bytes32 public root; /** * @dev Contract Methods */ constructor( address _reservee, uint256 _mainsaleStart, uint256 _presaleStart ) ERC721("Suckiverse DilDAO", "DILDAO") { payee = payable(msg.sender); mainsaleStart = _mainsaleStart; presaleStart = _presaleStart; } /************ * Metadata * ************/ function setTokenBaseURI(string memory _baseURI) external onlyOwner { tokenBaseURI = _baseURI; } function setUnrevealedURI(string memory _unrevealedUri) external onlyOwner { unrevealedURI = _unrevealedUri; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { bool revealed = bytes(tokenBaseURI).length > 0; if (!revealed) { return unrevealedURI; } require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(tokenBaseURI, _tokenId.toString())); } /*************** * Mint Setters * ***************/ function setPrice(uint256 _price) external onlyOwner { PRICE = _price; } function setAmountMintable(uint256 _amount) external onlyOwner { amountMintable = _amount; } function setMainsaleStart(uint256 _start) external onlyOwner { mainsaleStart = _start; } function setPresaleStart(uint256 _start) external onlyOwner { presaleStart = _start; } function suckiverse(address _suck) external onlyOwner { suck = IERC20(_suck); } /******* * Mint * *******/ function _mintActive() internal view returns (bool) { if (block.timestamp > mainsaleStart) { return true; } else { return false; } } function _presaleActive() internal view returns (bool) { if (block.timestamp > presaleStart) { return true; } else { return false; } } function tier(address user) internal view returns (uint256) { if (suck.totalSupply() / suck.balanceOf(msg.sender) <= 20) { return 420; } else if (suck.totalSupply() / suck.balanceOf(msg.sender) <= 50 ) { return 150; } else if (suck.totalSupply() / suck.balanceOf(msg.sender) <= 100) { return 69; } else if (suck.totalSupply() / suck.balanceOf(msg.sender) <= 200) { return 25; } else if (suck.totalSupply() / suck.balanceOf(msg.sender) <= 400) { return 12; } else if (suck.totalSupply() / suck.balanceOf(msg.sender) <= 1000) { return 5; } else { return 0; } } function mint(uint256 _quantity) external { require(presaleStart > 0 && mainsaleStart > 0, "Sale start times have not been set"); if (_mintActive() == true) { require(amountMinted[msg.sender] + _quantity <= amountMintable, "Quantity is more than mintable amount per account"); amountMinted[msg.sender] = _quantity + amountMinted[msg.sender]; } else if (_presaleActive() == true) { require(suck.balanceOf(msg.sender) > 0, "need at least 1 suck token"); require(amountMinted[msg.sender] + _quantity <= tier(msg.sender), "Quantity is higher than tier amount for this account"); amountMinted[msg.sender] = _quantity + amountMinted[msg.sender]; } else { revert("sale hasn't started"); } _safeMint(_quantity); } function _safeMint(uint256 _quantity) internal { require(_quantity > 0, "You must mint at least 1"); require(tokenSupply.current().add(_quantity) <= totalSupply, "This purchase would exceed totalSupply"); for (uint256 i = 0; i < _quantity; i++) { uint256 mintIndex = tokenSupply.current(); if (mintIndex < totalSupply) { tokenSupply.increment(); ERC721._safeMint(msg.sender, mintIndex); } } } function mintReserved() external onlyOwner { require(!reservesMinted, "Reserves have already been minted."); require(tokenSupply.current().add(RESERVED) <= totalSupply, "This mint would exceed totalSupply"); reservesMinted = true; for (uint256 i = 0; i < RESERVED; i++) { uint256 mintIndex = tokenSupply.current(); if (mintIndex < totalSupply) { tokenSupply.increment(); if (mintIndex > RESERVED - TEAM){ ERC721._safeMint(msg.sender, mintIndex); } else { ERC721._safeMint(reservee, mintIndex); } } } } /************** * Withdrawal * **************/ function withdraw() public { uint256 balance = address(this).balance; payable(payee).transfer(balance); } } // 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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; /** * @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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "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; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return recover(hash, r, vs); } else { revert("ECDSA: invalid signature length"); } } /** * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; } }
* @dev Contract Methods/
) ERC721("Suckiverse DilDAO", "DILDAO") { payee = payable(msg.sender); mainsaleStart = _mainsaleStart; presaleStart = _presaleStart; }
9,990,157
[ 1, 8924, 13063, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 262, 4232, 39, 27, 5340, 2932, 55, 9031, 17488, 463, 330, 18485, 3113, 315, 2565, 48, 18485, 7923, 288, 203, 3639, 8843, 1340, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 3639, 2774, 87, 5349, 1685, 273, 389, 81, 4167, 5349, 1685, 31, 203, 3639, 4075, 5349, 1685, 273, 389, 12202, 5349, 1685, 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 ]
// SPDX-License-Identifier: UNLICENSED // solhint-disable-next-line compiler-fixed, compiler-gt-0_8 pragma solidity ^0.8.0; import "./actions/StakingMsgProcessor.sol"; import "./interfaces/IActionMsgReceiver.sol"; import "./interfaces/IErc20Min.sol"; import "./interfaces/IStakingTypes.sol"; import "./interfaces/IVotingPower.sol"; import "./utils/ImmutableOwnable.sol"; import "./utils/Utils.sol"; /** * @title Staking * @notice It lets users stake $ZKP token for governance voting and rewards. * @dev At request of smart contracts and off-chain requesters, it computes * user "voting power" on the basis of tokens users stake. * It acts as the "ActionOracle" for the "RewardMaster": if stake terms presume * rewarding, it sends "messages" on stakes made and stakes claimed to the * "RewardMaster" contract which rewards stakers. * It supports multiple types of stakes (terms), which the owner may add or * remove without contract code upgrades. */ contract Staking is ImmutableOwnable, Utils, StakingMsgProcessor, IStakingTypes, IVotingPower { // solhint-disable var-name-mixedcase /// @notice Staking token IErc20Min public immutable TOKEN; /// @dev Block the contract deployed in uint256 public immutable START_BLOCK; /// @notice RewardMaster contract instance IActionMsgReceiver public immutable REWARD_MASTER; // solhint-enable var-name-mixedcase // Scale for min/max limits uint256 private constant SCALE = 1e18; /// @notice Total token amount staked /// @dev Staking token is deemed to have max total supply of 1e27 uint96 public totalStaked = 0; /// @dev Mapping from stake type to terms mapping(bytes4 => Terms) public terms; /// @dev Mapping from the staker address to stakes of the staker mapping(address => Stake[]) public stakes; // Special address to store global state address private constant GLOBAL_ACCOUNT = address(0); /// @dev Voting power integrants for each account // special case: GLOBAL_ACCOUNT for total voting power mapping(address => Power) public power; /// @dev Snapshots of each account // special case: GLOBAL_ACCOUNT for global snapshots mapping(address => Snapshot[]) private snapshots; /// @dev Emitted on a new stake made event StakeCreated( address indexed account, uint256 indexed stakeID, uint256 amount, bytes4 stakeType, uint256 lockedTill ); /// @dev Emitted on a stake claimed (i.e. "unstaked") event StakeClaimed(address indexed account, uint256 indexed stakeID); /// @dev Voting power delegated event Delegation( address indexed owner, address indexed from, address indexed to, uint256 stakeID, uint256 amount ); /// @dev New terms (for the given stake type) added event TermsAdded(bytes4 stakeType); /// @dev Terms (for the given stake type) are disabled event TermsDisabled(bytes4 stakeType); /// @dev Call to REWARD_MASTER reverted event RewardMasterRevert(address staker, uint256 stakeID); /** * @notice Sets staking token, owner and * @param stakingToken - Address of the {ZKPToken} contract * @param rewardMaster - Address of the {RewardMaster} contract * @param owner - Address of the owner account */ constructor( address stakingToken, address rewardMaster, address owner ) ImmutableOwnable(owner) { require( stakingToken != address(0) && rewardMaster != address(0), "Staking:C1" ); TOKEN = IErc20Min(stakingToken); REWARD_MASTER = IActionMsgReceiver(rewardMaster); START_BLOCK = blockNow(); } /** * @notice Stakes tokens * @dev This contract should be approve()'d for amount * @param amount - Amount to stake * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function stake( uint256 amount, bytes4 stakeType, bytes calldata data ) public returns (uint256) { return _createStake(msg.sender, amount, stakeType, data); } /** * @notice Approves this contract to transfer `amount` tokens from the `msg.sender` * and stakes these tokens. Only the owner of tokens (i.e. the staker) may call. * @dev This contract does not need to be approve()'d in advance - see EIP-2612 * @param owner - The owner of tokens being staked (i.e. the `msg.sender`) * @param amount - Amount to stake * @param v - "v" param of the signature from `owner` for "permit" * @param r - "r" param of the signature from `owner` for "permit" * @param s - "s" param of the signature from `owner` for "permit" * @param stakeType - Type of the stake * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @return stake ID */ function permitAndStake( address owner, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bytes4 stakeType, bytes calldata data ) external returns (uint256) { require(owner == msg.sender, "Staking: owner must be msg.sender"); TOKEN.permit(owner, address(this), amount, deadline, v, r, s); return _createStake(owner, amount, stakeType, data); } /** * @notice Claims staked token * @param stakeID - ID of the stake to claim * @param data - Arbitrary data for "RewardMaster" (zero, if inapplicable) * @param _isForced - Do not revert if "RewardMaster" fails */ function unstake( uint256 stakeID, bytes calldata data, bool _isForced ) external stakeExist(msg.sender, stakeID) { Stake memory _stake = stakes[msg.sender][stakeID]; require(_stake.claimedAt == 0, "Staking: Stake claimed"); require(_stake.lockedTill < safe32TimeNow(), "Staking: Stake locked"); if (_stake.delegatee != address(0)) { _undelegatePower(_stake.delegatee, msg.sender, _stake.amount); } _removePower(msg.sender, _stake.amount); stakes[msg.sender][stakeID].claimedAt = safe32TimeNow(); totalStaked = safe96(uint256(totalStaked) - uint256(_stake.amount)); emit StakeClaimed(msg.sender, stakeID); // known contract - reentrancy guard and `safeTransfer` unneeded require( TOKEN.transfer(msg.sender, _stake.amount), "Staking: transfer failed" ); Terms memory _terms = terms[_stake.stakeType]; if (_terms.isRewarded) { _sendUnstakedMsg(msg.sender, _stake, data, _isForced); } } /** * @notice Updates vote delegation * @param stakeID - ID of the stake to delegate votes uber * @param to - address to delegate to */ function delegate(uint256 stakeID, address to) public stakeExist(msg.sender, stakeID) { require( to != GLOBAL_ACCOUNT, "Staking: Can't delegate to GLOBAL_ACCOUNT" ); Stake memory s = stakes[msg.sender][stakeID]; require(s.claimedAt == 0, "Staking: Stake claimed"); require(s.delegatee != to, "Staking: Already delegated"); if (s.delegatee == address(0)) { _delegatePower(msg.sender, to, s.amount); } else { if (to == msg.sender) { _undelegatePower(s.delegatee, msg.sender, s.amount); } else { _reDelegatePower(s.delegatee, to, s.amount); } } emit Delegation(msg.sender, s.delegatee, to, stakeID, s.amount); stakes[msg.sender][stakeID].delegatee = to; } /** * @notice Delegates voting power of stake back to self * @param stakeID - ID of the stake to delegate votes back to self */ function undelegate(uint256 stakeID) external { delegate(stakeID, msg.sender); } /// @notice Returns number of stakes of given _account function stakesNum(address _account) external view returns (uint256) { return stakes[_account].length; } /// @notice Returns stakes of given account function accountStakes(address _account) external view returns (Stake[] memory) { Stake[] memory _stakes = stakes[_account]; return _stakes; } /// @inheritdoc IVotingPower function totalVotingPower() external view override returns (uint256) { Power memory _power = power[GLOBAL_ACCOUNT]; return _power.own + _power.delegated; } /// @inheritdoc IVotingPower function totalPower() external view override returns (Power memory) { return power[GLOBAL_ACCOUNT]; } /// @inheritdoc IVotingPower function latestGlobalsSnapshotBlock() public view override returns (uint256) { return latestSnapshotBlock(GLOBAL_ACCOUNT); } /// @inheritdoc IVotingPower function latestSnapshotBlock(address _account) public view override returns (uint256) { if (snapshots[_account].length == 0) return 0; return snapshots[_account][snapshots[_account].length - 1].beforeBlock; } /// @inheritdoc IVotingPower function globalsSnapshotLength() external view override returns (uint256) { return snapshots[GLOBAL_ACCOUNT].length; } /// @inheritdoc IVotingPower function snapshotLength(address _account) external view override returns (uint256) { return snapshots[_account].length; } /// @inheritdoc IVotingPower function globalsSnapshot(uint256 _index) external view override returns (Snapshot memory) { return snapshots[GLOBAL_ACCOUNT][_index]; } /// @inheritdoc IVotingPower function snapshot(address _account, uint256 _index) external view override returns (Snapshot memory) { return snapshots[_account][_index]; } /// @inheritdoc IVotingPower function globalSnapshotAt(uint256 blockNum, uint256 hint) external view override returns (Snapshot memory) { return _snapshotAt(GLOBAL_ACCOUNT, blockNum, hint); } /// @inheritdoc IVotingPower function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view override returns (Snapshot memory) { return _snapshotAt(_account, blockNum, hint); } /// Only for the owner functions /// @notice Adds a new stake type with given terms /// @dev May be only called by the {OWNER} function addTerms(bytes4 stakeType, Terms memory _terms) external onlyOwner nonZeroStakeType(stakeType) { Terms memory existingTerms = terms[stakeType]; require(!_isDefinedTerms(existingTerms), "Staking:E1"); require(_terms.isEnabled, "Staking:E2"); uint256 _now = timeNow(); if (_terms.allowedTill != 0) { require(_terms.allowedTill > _now, "Staking:E3"); require(_terms.allowedTill > _terms.allowedSince, "Staking:E4"); } if (_terms.maxAmountScaled != 0) { require( _terms.maxAmountScaled > _terms.minAmountScaled, "Staking:E5" ); } // only one of three "lock time" parameters must be non-zero if (_terms.lockedTill != 0) { require( _terms.exactLockPeriod == 0 && _terms.minLockPeriod == 0, "Staking:E6" ); require( _terms.lockedTill > _now && _terms.lockedTill >= _terms.allowedTill, "Staking:E7" ); } else { require( // one of two params must be non-zero (_terms.exactLockPeriod == 0) != (_terms.minLockPeriod == 0), "Staking:E8" ); } terms[stakeType] = _terms; emit TermsAdded(stakeType); } function disableTerms(bytes4 stakeType) external onlyOwner nonZeroStakeType(stakeType) { Terms memory _terms = terms[stakeType]; require(_isDefinedTerms(terms[stakeType]), "Staking:E9"); require(_terms.isEnabled, "Staking:EA"); terms[stakeType].isEnabled = false; emit TermsDisabled(stakeType); } /// Internal and private functions follow function _createStake( address staker, uint256 amount, bytes4 stakeType, bytes calldata data ) internal nonZeroStakeType(stakeType) returns (uint256) { Terms memory _terms = terms[stakeType]; require(_terms.isEnabled, "Staking: Terms unknown or disabled"); require(amount > 0, "Staking: Amount not set"); uint256 _totalStake = amount + uint256(totalStaked); require(_totalStake < 2**96, "Staking: Too big amount"); require( _terms.minAmountScaled == 0 || amount >= SCALE * _terms.minAmountScaled, "Staking: Too small amount" ); require( _terms.maxAmountScaled == 0 || amount <= SCALE * _terms.maxAmountScaled, "Staking: Too large amount" ); uint32 _now = safe32TimeNow(); require( _terms.allowedSince == 0 || _now >= _terms.allowedSince, "Staking: Not yet allowed" ); require( _terms.allowedTill == 0 || _terms.allowedTill > _now, "Staking: Not allowed anymore" ); // known contract - reentrancy guard and `safeTransferFrom` unneeded require( TOKEN.transferFrom(staker, address(this), amount), "Staking: transferFrom failed" ); uint256 stakeID = stakes[staker].length; uint32 lockedTill = _terms.lockedTill; if (lockedTill == 0) { uint256 period = _terms.exactLockPeriod == 0 ? _terms.minLockPeriod : _terms.exactLockPeriod; lockedTill = safe32(period + _now); } Stake memory _stake = Stake( uint32(stakeID), // overflow risk ignored stakeType, _now, // stakedAt lockedTill, 0, // claimedAt uint96(amount), address(0) // no delegatee ); stakes[staker].push(_stake); totalStaked = uint96(_totalStake); _addPower(staker, amount); emit StakeCreated(staker, stakeID, amount, stakeType, lockedTill); if (_terms.isRewarded) { _sendStakedMsg(staker, _stake, data); } return stakeID; } function _addPower(address to, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _removePower(address from, uint256 amount) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); } function _delegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(GLOBAL_ACCOUNT); _takeSnapshot(to); _takeSnapshot(from); power[GLOBAL_ACCOUNT].own -= uint96(amount); power[from].own -= uint96(amount); power[GLOBAL_ACCOUNT].delegated += uint96(amount); power[to].delegated += uint96(amount); } function _reDelegatePower( address from, address to, uint256 amount ) private { _takeSnapshot(to); _takeSnapshot(from); power[from].delegated -= uint96(amount); power[to].delegated += uint96(amount); } function _undelegatePower( address from, address to, uint256 amount ) private { power[GLOBAL_ACCOUNT].delegated -= uint96(amount); power[from].delegated -= uint96(amount); power[GLOBAL_ACCOUNT].own += uint96(amount); power[to].own += uint96(amount); } function _takeSnapshot(address _account) internal { uint32 curBlockNum = safe32BlockNow(); if (latestSnapshotBlock(_account) < curBlockNum) { // make new snapshot as the latest one taken before current block snapshots[_account].push( Snapshot( curBlockNum, power[_account].own, power[_account].delegated ) ); } } function _snapshotAt( address _account, uint256 blockNum, uint256 hint ) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); Snapshot[] storage snapshotsInfo = snapshots[_account]; if ( // hint is correct? hint <= snapshotsInfo.length && (hint == 0 || snapshotsInfo[hint - 1].beforeBlock < blockNum) && (hint == snapshotsInfo.length || snapshotsInfo[hint].beforeBlock >= blockNum) ) { // yes, return the hinted snapshot if (hint < snapshotsInfo.length) { return snapshotsInfo[hint]; } else { return Snapshot( uint32(blockNum), power[_account].own, power[_account].delegated ); } } // no, fall back to binary search else return _snapshotAt(_account, blockNum); } function _snapshotAt(address _account, uint256 blockNum) internal view returns (Snapshot memory) { _sanitizeBlockNum(blockNum); // https://en.wikipedia.org/wiki/Binary_search_algorithm Snapshot[] storage snapshotsInfo = snapshots[_account]; uint256 index; uint256 low = 0; uint256 high = snapshotsInfo.length; while (low < high) { uint256 mid = (low + high) / 2; if (snapshotsInfo[mid].beforeBlock > blockNum) { high = mid; } else { low = mid + 1; } } // `low` is the exclusive upper bound. Find the inclusive upper bounds and set to index if (low > 0 && snapshotsInfo[low - 1].beforeBlock == blockNum) { return snapshotsInfo[low - 1]; } else { index = low; } // If index is equal to snapshot array length, then no update made after the requested blockNum. // This means the latest value is the right one. if (index == snapshotsInfo.length) { return Snapshot( uint32(blockNum), uint96(power[_account].own), uint96(power[_account].delegated) ); } else { return snapshotsInfo[index]; } } function _sanitizeBlockNum(uint256 blockNum) private view { require(blockNum <= safe32BlockNow(), "Staking: Too big block number"); } function _isDefinedTerms(Terms memory _terms) internal pure returns (bool) { return (_terms.minLockPeriod != 0) || (_terms.exactLockPeriod != 0) || (_terms.lockedTill != 0); } function _sendStakedMsg( address staker, Stake memory _stake, bytes calldata data ) internal { bytes4 action = _encodeStakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { revert("Staking: onStake msg failed"); } } function _sendUnstakedMsg( address staker, Stake memory _stake, bytes calldata data, bool _isForced ) internal { bytes4 action = _encodeUnstakeActionType(_stake.stakeType); bytes memory message = _packStakingActionMsg(staker, _stake, data); // known contract - reentrancy guard unneeded // solhint-disable-next-line no-empty-blocks try REWARD_MASTER.onAction(action, message) {} catch { emit RewardMasterRevert(staker, _stake.id); // REWARD_MASTER must be unable to revert forced calls require(_isForced, "Staking: REWARD_MASTER reverts"); } } modifier stakeExist(address staker, uint256 stakeID) { require( stakes[staker].length > stakeID, "Staking: Stake doesn't exist" ); _; } modifier nonZeroStakeType(bytes4 stakeType) { require(stakeType != bytes4(0), "Staking: Invalid stake type 0"); _; } } // SPDX-License-Identifier: UNLICENSED // solhint-disable-next-line compiler-fixed, compiler-gt-0_8 pragma solidity ^0.8.0; import "../interfaces/IStakingTypes.sol"; abstract contract StakingMsgProcessor { bytes4 internal constant STAKE_ACTION = bytes4(keccak256("stake")); bytes4 internal constant UNSTAKE_ACTION = bytes4(keccak256("unstake")); function _encodeStakeActionType(bytes4 stakeType) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked(STAKE_ACTION, stakeType))); } function _encodeUnstakeActionType(bytes4 stakeType) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked(UNSTAKE_ACTION, stakeType))); } function _packStakingActionMsg( address staker, IStakingTypes.Stake memory stake, bytes calldata data ) internal pure returns (bytes memory) { return abi.encodePacked( staker, // address stake.amount, // uint96 stake.id, // uint32 stake.stakedAt, // uint32 stake.lockedTill, // uint32 stake.claimedAt, // uint32 data // bytes ); } // For efficiency we use "packed" (rather than "ABI") encoding. // It results in shorter data, but requires custom unpack function. function _unpackStakingActionMsg(bytes memory message) internal pure returns ( address staker, uint96 amount, uint32 id, uint32 stakedAt, uint32 lockedTill, uint32 claimedAt, bytes memory data ) { // staker, amount, id and 3 timestamps occupy exactly 48 bytes // (`data` may be of zero length) require(message.length >= 48, "SMP: unexpected msg length"); uint256 stakerAndAmount; uint256 idAndStamps; // solhint-disable-next-line no-inline-assembly assembly { // the 1st word (32 bytes) contains the `message.length` // we need the (entire) 2nd word .. stakerAndAmount := mload(add(message, 0x20)) // .. and (16 bytes of) the 3rd word idAndStamps := mload(add(message, 0x40)) } staker = address(uint160(stakerAndAmount >> 96)); amount = uint96(stakerAndAmount & 0xFFFFFFFFFFFFFFFFFFFFFFFF); id = uint32((idAndStamps >> 224) & 0xFFFFFFFF); stakedAt = uint32((idAndStamps >> 192) & 0xFFFFFFFF); lockedTill = uint32((idAndStamps >> 160) & 0xFFFFFFFF); claimedAt = uint32((idAndStamps >> 128) & 0xFFFFFFFF); uint256 dataLength = message.length - 48; data = new bytes(dataLength); for (uint256 i = 0; i < dataLength; i++) { data[i] = message[i + 48]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IActionMsgReceiver { function onAction(bytes4 action, bytes memory message) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IErc20Min { /// @dev ERC-20 `balanceOf` function balanceOf(address account) external view returns (uint256); /// @dev ERC-20 `transfer` function transfer(address recipient, uint256 amount) external returns (bool); /// @dev ERC-20 `transferFrom` function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /// @dev EIP-2612 `permit` function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-fixed, compiler-gt-0_8 pragma solidity ^0.8.0; interface IStakingTypes { // Stake type terms struct Terms { // if stakes of this kind allowed bool isEnabled; // if messages on stakes to be sent to the {RewardMaster} bool isRewarded; // limit on the minimum amount staked, no limit if zero uint32 minAmountScaled; // limit on the maximum amount staked, no limit if zero uint32 maxAmountScaled; // Stakes not accepted before this time, has no effect if zero uint32 allowedSince; // Stakes not accepted after this time, has no effect if zero uint32 allowedTill; // One (at least) of the following three params must be non-zero // if non-zero, overrides both `exactLockPeriod` and `minLockPeriod` uint32 lockedTill; // ignored if non-zero `lockedTill` defined, overrides `minLockPeriod` uint32 exactLockPeriod; // has effect only if both `lockedTill` and `exactLockPeriod` are zero uint32 minLockPeriod; } struct Stake { // index in the `Stake[]` array of `stakes` uint32 id; // defines Terms bytes4 stakeType; // time this stake was created at uint32 stakedAt; // time this stake can be claimed at uint32 lockedTill; // time this stake was claimed at (unclaimed if 0) uint32 claimedAt; // amount of tokens on this stake (assumed to be less 1e27) uint96 amount; // address stake voting power is delegated to address delegatee; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IStaking interface IVotingPower { struct Snapshot { uint32 beforeBlock; uint96 ownPower; uint96 delegatedPower; } /// @dev Voting power integrants struct Power { uint96 own; // voting power that remains after delegating to others uint96 delegated; // voting power delegated by others } /// @notice Returns total voting power staked /// @dev "own" and "delegated" voting power summed up function totalVotingPower() external view returns (uint256); /// @notice Returns total "own" and total "delegated" voting power separately /// @dev Useful, if "own" and "delegated" voting power treated differently function totalPower() external view returns (Power memory); /// @notice Returns global snapshot for given block /// @param blockNum - block number to get state at /// @param hint - off-chain computed index of the required snapshot function globalSnapshotAt(uint256 blockNum, uint256 hint) external view returns (Snapshot memory); /// @notice Returns snapshot on given block for given account /// @param _account - account to get snapshot for /// @param blockNum - block number to get state at /// @param hint - off-chain computed index of the required snapshot function snapshotAt( address _account, uint256 blockNum, uint256 hint ) external view returns (Snapshot memory); /// @dev Returns block number of the latest global snapshot function latestGlobalsSnapshotBlock() external view returns (uint256); /// @dev Returns block number of the given account latest snapshot function latestSnapshotBlock(address _account) external view returns (uint256); /// @dev Returns number of global snapshots function globalsSnapshotLength() external view returns (uint256); /// @dev Returns number of snapshots for given account function snapshotLength(address _account) external view returns (uint256); /// @dev Returns global snapshot at given index function globalsSnapshot(uint256 _index) external view returns (Snapshot memory); /// @dev Returns snapshot at given index for given account function snapshot(address _account, uint256 _index) external view returns (Snapshot memory); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-fixed, compiler-gt-0_8 pragma solidity ^0.8.0; /// @title Staking abstract contract ImmutableOwnable { /// @notice The owner who has privileged rights // solhint-disable-next-line var-name-mixedcase address public immutable OWNER; /// @dev Throws if called by any account other than the {OWNER}. modifier onlyOwner() { require(OWNER == msg.sender, "ImmOwn: unauthorized"); _; } constructor(address _owner) { require(_owner != address(0), "ImmOwn: zero owner address"); OWNER = _owner; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-fixed, compiler-gt-0_8 pragma solidity ^0.8.0; abstract contract Utils { function safe32(uint256 n) internal pure returns (uint32) { require(n < 2**32, "UNSAFE32"); return uint32(n); } function safe96(uint256 n) internal pure returns (uint96) { require(n < 2**96, "UNSAFE96"); return uint96(n); } function safe128(uint256 n) internal pure returns (uint128) { require(n < 2**128, "UNSAFE128"); return uint128(n); } function safe160(uint256 n) internal pure returns (uint160) { require(n < 2**160, "UNSAFE160"); return uint160(n); } function safe32TimeNow() internal view returns (uint32) { return safe32(timeNow()); } function safe32BlockNow() internal view returns (uint32) { return safe32(blockNow()); } /// @dev Returns the current block timestamp (added to ease testing) function timeNow() internal view virtual returns (uint256) { return block.timestamp; } /// @dev Returns the current block number (added to ease testing) function blockNow() internal view virtual returns (uint256) { return block.number; } }
For efficiency we use "packed" (rather than "ABI") encoding. It results in shorter data, but requires custom unpack function. staker, amount, id and 3 timestamps occupy exactly 48 bytes (`data` may be of zero length) solhint-disable-next-line no-inline-assembly the 1st word (32 bytes) contains the `message.length` we need the (entire) 2nd word .. .. and (16 bytes of) the 3rd word
function _unpackStakingActionMsg(bytes memory message) internal pure returns ( address staker, uint96 amount, uint32 id, uint32 stakedAt, uint32 lockedTill, uint32 claimedAt, bytes memory data ) { require(message.length >= 48, "SMP: unexpected msg length"); uint256 stakerAndAmount; uint256 idAndStamps; assembly { stakerAndAmount := mload(add(message, 0x20)) idAndStamps := mload(add(message, 0x40)) } staker = address(uint160(stakerAndAmount >> 96)); amount = uint96(stakerAndAmount & 0xFFFFFFFFFFFFFFFFFFFFFFFF); id = uint32((idAndStamps >> 224) & 0xFFFFFFFF); stakedAt = uint32((idAndStamps >> 192) & 0xFFFFFFFF); lockedTill = uint32((idAndStamps >> 160) & 0xFFFFFFFF); claimedAt = uint32((idAndStamps >> 128) & 0xFFFFFFFF); uint256 dataLength = message.length - 48; data = new bytes(dataLength); for (uint256 i = 0; i < dataLength; i++) { data[i] = message[i + 48]; } }
1,328,074
[ 1, 1290, 30325, 732, 999, 315, 2920, 329, 6, 261, 86, 4806, 2353, 315, 2090, 45, 7923, 2688, 18, 2597, 1686, 316, 19623, 501, 16, 1496, 4991, 1679, 6167, 445, 18, 384, 6388, 16, 3844, 16, 612, 471, 890, 11267, 18928, 93, 8950, 9934, 1731, 21863, 892, 68, 2026, 506, 434, 3634, 769, 13, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 326, 404, 334, 2076, 261, 1578, 1731, 13, 1914, 326, 1375, 2150, 18, 2469, 68, 732, 1608, 326, 261, 319, 577, 13, 576, 4880, 2076, 6116, 6116, 471, 261, 2313, 1731, 434, 13, 326, 890, 13623, 2076, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17309, 510, 6159, 1803, 3332, 12, 3890, 3778, 883, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 203, 5411, 1758, 384, 6388, 16, 203, 5411, 2254, 10525, 3844, 16, 203, 5411, 2254, 1578, 612, 16, 203, 5411, 2254, 1578, 384, 9477, 861, 16, 203, 5411, 2254, 1578, 8586, 56, 737, 16, 203, 5411, 2254, 1578, 7516, 329, 861, 16, 203, 5411, 1731, 3778, 501, 203, 3639, 262, 203, 565, 288, 203, 3639, 2583, 12, 2150, 18, 2469, 1545, 9934, 16, 315, 55, 4566, 30, 9733, 1234, 769, 8863, 203, 203, 3639, 2254, 5034, 384, 6388, 1876, 6275, 31, 203, 3639, 2254, 5034, 612, 1876, 8860, 87, 31, 203, 3639, 19931, 288, 203, 5411, 384, 6388, 1876, 6275, 519, 312, 945, 12, 1289, 12, 2150, 16, 374, 92, 3462, 3719, 203, 5411, 612, 1876, 8860, 87, 519, 312, 945, 12, 1289, 12, 2150, 16, 374, 92, 7132, 3719, 203, 3639, 289, 203, 203, 3639, 384, 6388, 273, 1758, 12, 11890, 16874, 12, 334, 6388, 1876, 6275, 1671, 19332, 10019, 203, 3639, 3844, 273, 2254, 10525, 12, 334, 6388, 1876, 6275, 473, 374, 6356, 8998, 8998, 8998, 8998, 18343, 1769, 203, 203, 3639, 612, 273, 2254, 1578, 12443, 350, 1876, 8860, 87, 1671, 576, 3247, 13, 473, 374, 28949, 1769, 203, 3639, 384, 9477, 861, 273, 2254, 1578, 12443, 350, 1876, 8860, 87, 1671, 20217, 13, 473, 374, 28949, 1769, 203, 3639, 8586, 56, 737, 273, 2254, 1578, 12443, 350, 1876, 8860, 87, 1671, 25430, 13, 473, 374, 28949, 1769, 2 ]
./full_match/288/0xCD43CEa89DF8fE39031C03c24BC24480e942470B/sources/contracts/insured-bridge/ovm/OVM_OETH_BridgeDepositBox.sol
l2Eth is ETH on Optimism. This acts as both an ERC20 and ETH on the OVM. In production is deployed at address 0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000. We need to know the address in this contract as the Optimism bridge does not support WETH so we need to unwrap to ETH first then send over ETH. The L1 ETH Wrapper contract receives ETH, wraps it to WETH and sends it to the BridgePool. This enables the us to keep the same L1 contracts while supporting Optimsim.
contract OVM_OETH_BridgeDepositBox is OVM_BridgeDepositBox { address public l2Eth; address public l1EthWrapper; constructor( address _crossDomainAdmin, uint64 _minimumBridgingDelay, uint256 _chainId, address _l1Weth, address _l2Eth, address _l1EthWrapper, address timerAddress ) OVM_BridgeDepositBox(_crossDomainAdmin, _minimumBridgingDelay, _chainId, _l1Weth, timerAddress) { l2Eth = _l2Eth; l1EthWrapper = _l1EthWrapper; } function bridgeTokens(address l2Token, uint32 l1Gas) public override nonReentrant() { uint256 bridgeDepositBoxBalance = TokenLike(l2Token).balanceOf(address(this)); require(bridgeDepositBoxBalance > 0, "can't bridge zero tokens"); require(canBridge(l2Token), "non-whitelisted token or last bridge too recent"); whitelistedTokens[l2Token].lastBridgeTime = uint64(getCurrentTime()); address bridgePool = whitelistedTokens[l2Token].l1BridgePool; if (whitelistedTokens[l2Token].l1Token == l1Weth) { WETH9Like(l2Token).withdraw(bridgeDepositBoxBalance); l2Token = l2Eth; bridgePool = l1EthWrapper; } IL2ERC20Bridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo( ); emit TokensBridged(l2Token, bridgeDepositBoxBalance, l1Gas, msg.sender); } function bridgeTokens(address l2Token, uint32 l1Gas) public override nonReentrant() { uint256 bridgeDepositBoxBalance = TokenLike(l2Token).balanceOf(address(this)); require(bridgeDepositBoxBalance > 0, "can't bridge zero tokens"); require(canBridge(l2Token), "non-whitelisted token or last bridge too recent"); whitelistedTokens[l2Token].lastBridgeTime = uint64(getCurrentTime()); address bridgePool = whitelistedTokens[l2Token].l1BridgePool; if (whitelistedTokens[l2Token].l1Token == l1Weth) { WETH9Like(l2Token).withdraw(bridgeDepositBoxBalance); l2Token = l2Eth; bridgePool = l1EthWrapper; } IL2ERC20Bridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo( ); emit TokensBridged(l2Token, bridgeDepositBoxBalance, l1Gas, msg.sender); } receive() external payable {} fallback() external payable {} }
7,105,903
[ 1, 80, 22, 41, 451, 353, 512, 2455, 603, 19615, 6228, 18, 1220, 22668, 487, 3937, 392, 4232, 39, 3462, 471, 512, 2455, 603, 326, 531, 7397, 18, 657, 12449, 353, 19357, 622, 1758, 374, 92, 22097, 22097, 22097, 22097, 22097, 22097, 22097, 22097, 22097, 2787, 18, 1660, 1608, 358, 5055, 326, 1758, 316, 333, 6835, 487, 326, 19615, 6228, 10105, 1552, 486, 2865, 678, 1584, 44, 1427, 732, 1608, 358, 11014, 358, 512, 2455, 1122, 1508, 1366, 1879, 512, 2455, 18, 1021, 511, 21, 512, 2455, 18735, 6835, 17024, 512, 2455, 16, 9059, 518, 358, 678, 1584, 44, 471, 9573, 518, 358, 326, 24219, 2864, 18, 1220, 19808, 326, 584, 358, 3455, 326, 1967, 511, 21, 20092, 1323, 22930, 19615, 9812, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 531, 7397, 67, 51, 1584, 44, 67, 13691, 758, 1724, 3514, 353, 531, 7397, 67, 13691, 758, 1724, 3514, 288, 203, 565, 1758, 1071, 328, 22, 41, 451, 31, 203, 565, 1758, 1071, 328, 21, 41, 451, 3611, 31, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 14653, 3748, 4446, 16, 203, 3639, 2254, 1105, 389, 15903, 38, 1691, 1998, 6763, 16, 203, 3639, 2254, 5034, 389, 5639, 548, 16, 203, 3639, 1758, 389, 80, 21, 59, 546, 16, 203, 3639, 1758, 389, 80, 22, 41, 451, 16, 203, 3639, 1758, 389, 80, 21, 41, 451, 3611, 16, 203, 3639, 1758, 5441, 1887, 203, 203, 565, 262, 531, 7397, 67, 13691, 758, 1724, 3514, 24899, 14653, 3748, 4446, 16, 389, 15903, 38, 1691, 1998, 6763, 16, 389, 5639, 548, 16, 389, 80, 21, 59, 546, 16, 5441, 1887, 13, 288, 203, 3639, 328, 22, 41, 451, 273, 389, 80, 22, 41, 451, 31, 203, 3639, 328, 21, 41, 451, 3611, 273, 389, 80, 21, 41, 451, 3611, 31, 203, 565, 289, 203, 203, 565, 445, 10105, 5157, 12, 2867, 328, 22, 1345, 16, 2254, 1578, 328, 21, 27998, 13, 1071, 3849, 1661, 426, 8230, 970, 1435, 288, 203, 3639, 2254, 5034, 10105, 758, 1724, 3514, 13937, 273, 3155, 8804, 12, 80, 22, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 18337, 758, 1724, 3514, 13937, 405, 374, 16, 315, 4169, 1404, 10105, 3634, 2430, 8863, 203, 3639, 2583, 12, 4169, 13691, 12, 80, 22, 1345, 3631, 315, 2 ]
/* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./IFoxGameNFTTraits.sol"; import "./IFoxGameNFT.sol"; contract FoxGameNFTTraits is IFoxGameNFTTraits, Ownable { using Strings for uint256; // add [uint256].toString() // Struct to store each trait's data for metadata and rendering struct Trait { string name; string png; } // Mapping of traits to metadata display names string[3] private _players = [ "Rabbit", "Fox", "Hunter" ]; string[4] private _advantages = [ "8", "7", "6", "5" ]; // FoxGames NFT address reference IFoxGameNFT private foxNFT; // Storage of each traits name and base64 PNG data [TRAIT][TRAIT VALUE] mapping(uint8 => mapping(uint8 => Trait)) public traitData; constructor() {} /** * Update the NFT contract address outside constructor as it would * create a cyclic dependency. */ function setNFTContract(address _address) external onlyOwner { foxNFT = IFoxGameNFT(_address); } /** * Upload trait art to blockchain! * @param traitTypeId trait name id (0 corresponds to "fur") * @param traitValueId trait value id (3 corresponds to "black") * @param traits array of trait [name, png] (e.g,. [bandana, {bytes}]) */ function uploadTraits(uint8 traitTypeId, uint8[] calldata traitValueId, string[][2] calldata traits) external onlyOwner { require(traitValueId.length == traits.length, "Mismatched inputs"); for (uint8 i = 0; i < traits.length; i++) { traitData[traitTypeId][traitValueId[i]] = Trait( traits[i][0], traits[i][1] ); } } /** * generates an <image> element using base64 encoded PNGs * @param trait the trait storing the PNG data * @return the <image> element */ function _drawTrait(Trait memory trait) internal pure returns (string memory) { return string(abi.encodePacked( '<image x="4" y="4" width="32" height="32" image-rendering="pixelated" preserveAspectRatio="xMidYMid" xlink:href="data:image/png;base64,', trait.png, '"/>' )); } /** * Generates an entire SVG by composing multiple <image> elements of PNGs * @param t token trait struct * @return layered SVG */ function _drawSVG(IFoxGameNFT.Traits memory t) internal view returns (string memory) { string memory svg; if (t.kind == IFoxGameNFT.Kind.RABBIT) { svg = string(abi.encodePacked( _drawTrait(traitData[0][t.traits[0]]), // Fur _drawTrait(traitData[1][t.traits[1]]), // Paws _drawTrait(traitData[2][t.traits[2]]), // Mouth _drawTrait(traitData[3][t.traits[3]]), // Nose _drawTrait(traitData[4][t.traits[4]]), // Eyes _drawTrait(traitData[5][t.traits[5]]), // Ears _drawTrait(traitData[6][t.traits[6]]) // Head )); } else if (t.kind == IFoxGameNFT.Kind.FOX) { svg = string(abi.encodePacked( _drawTrait(traitData[8][t.traits[0]]), // Tail _drawTrait(traitData[7][t.traits[1]]), // Fur _drawTrait(traitData[9][t.traits[2]]), // Feet _drawTrait(traitData[10][t.traits[3]]), // Neck _drawTrait(traitData[11][t.traits[4]]), // Mouth _drawTrait(traitData[12][t.traits[5]]), // Eyes _drawTrait(traitData[13][t.advantage]) // Cunning )); } else { // HUNTER svg = string(abi.encodePacked( _drawTrait(traitData[14][t.traits[0]]), // Clothes _drawTrait(traitData[15][t.traits[1]]), // Marksman _drawTrait(traitData[16][t.traits[2]]), // Neck _drawTrait(traitData[17][t.traits[3]]), // Mouth _drawTrait(traitData[18][t.traits[4]]), // Eyes _drawTrait(traitData[19][t.traits[5]]), // Hat _drawTrait(traitData[20][t.advantage]) // Marksman )); } return string(abi.encodePacked( '<svg width="100%" height="100%" version="1.1" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">', svg, "</svg>" )); } /** * Generates an attribute for the attributes array in the ERC721 metadata standard * @param traitType the trait type to reference as the metadata key * @param value the token's trait associated with the key * @return a JSON dictionary for the single attribute */ function _attributeForTypeAndValue(string memory traitType, string memory value) internal pure returns (string memory) { return string(abi.encodePacked( '{"trait_type":"', traitType, '","value":"', value, '"}' )); } /** * Generates an array composed of all the individual traits and values * @param tokenId the ID of the token to compose the metadata for * @return traits JSON array of all of the attributes for given token ID */ function _compileAttributes(uint16 tokenId, IFoxGameNFT.Traits memory t) internal view returns (string memory traits) { if (t.kind == IFoxGameNFT.Kind.RABBIT) { traits = string(abi.encodePacked( _attributeForTypeAndValue("Fur", traitData[0][t.traits[0]].name), ",", _attributeForTypeAndValue("Paws", traitData[1][t.traits[1]].name), ",", _attributeForTypeAndValue("Mouth", traitData[2][t.traits[2]].name), ",", _attributeForTypeAndValue("Nose", traitData[3][t.traits[3]].name), ",", _attributeForTypeAndValue("Eyes", traitData[4][t.traits[4]].name), ",", _attributeForTypeAndValue("Ears", traitData[5][t.traits[5]].name), ",", _attributeForTypeAndValue("Head", traitData[6][t.traits[6]].name), "," )); } else if (t.kind == IFoxGameNFT.Kind.FOX) { traits = string(abi.encodePacked( _attributeForTypeAndValue("Tail", traitData[7][t.traits[0]].name), ",", _attributeForTypeAndValue("Fur", traitData[8][t.traits[1]].name), ",", _attributeForTypeAndValue("Feet", traitData[9][t.traits[2]].name), ",", _attributeForTypeAndValue("Neck", traitData[10][t.traits[3]].name), ",", _attributeForTypeAndValue("Mouth", traitData[11][t.traits[4]].name), ",", _attributeForTypeAndValue("Eyes", traitData[12][t.traits[5]].name), ",", _attributeForTypeAndValue("Cunning Score", _advantages[t.advantage]), "," )); } else { // HUNTER traits = string(abi.encodePacked( _attributeForTypeAndValue("Clothes", traitData[13][t.traits[0]].name), ",", _attributeForTypeAndValue("Marksman", traitData[14][t.traits[1]].name), ",", _attributeForTypeAndValue("Neck", traitData[15][t.traits[2]].name), ",", _attributeForTypeAndValue("Mouth", traitData[16][t.traits[3]].name), ",", _attributeForTypeAndValue("Eyes", traitData[17][t.traits[4]].name), ",", _attributeForTypeAndValue("Hat", traitData[18][t.traits[5]].name), ",", _attributeForTypeAndValue("Marksman Score", _advantages[t.advantage]), "," )); } return string(abi.encodePacked( '[', traits, '{"trait_type":"Generation","value":', tokenId <= foxNFT.getMaxGEN0Players() ? '"GEN 0"' : '"GEN 1"', '},{"trait_type":"Type","value":', _players[uint8(t.kind)], '}]' )); } /** * ERC720 token URI interface. Generates a base64 encoded metadata response * without referencing off-chain content. * @param tokenId the ID of the token to generate the metadata for * @return a base64 encoded JSON dictionary of the token's metadata and SVG */ function tokenURI(uint16 tokenId) external view override returns (string memory) { IFoxGameNFT.Traits memory traits = foxNFT.getTraits(tokenId); string memory metadata = string(abi.encodePacked( '{"name": "', _players[uint8(traits.kind)], " #", uint256(tokenId).toString(), '", "description": "The metaverse mainland is full of creatures. Around the Farm, an abundance of Rabbits scurry to harvest CARROT. Alongside Farmers, they expand the farm and multiply their earnings. There', "'", 's only one small problem -- the farm has grown too big and a new threat of nature has entered the game.", "image": "data:image/svg+xml;base64,', _base64(bytes(_drawSVG(traits))), '", "attributes":', _compileAttributes(tokenId, traits), "}" )); return string(abi.encodePacked( "data:application/json;base64,", _base64(bytes(metadata)) )); } /** BASE 64 - Written by Brech Devos */ string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function _base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); // solhint-disable-next-line no-inline-assembly assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameNFTTraits { function tokenURI(uint16 tokenId) external view returns (string memory); } /* ███████╗ ██████╗ ██╗ ██╗ ██████╗ █████╗ ███╗ ███╗███████╗ ██╔════╝██╔═══██╗╚██╗██╔╝ ██╔════╝ ██╔══██╗████╗ ████║██╔════╝ █████╗ ██║ ██║ ╚███╔╝ ██║ ███╗███████║██╔████╔██║█████╗ ██╔══╝ ██║ ██║ ██╔██╗ ██║ ██║██╔══██║██║╚██╔╝██║██╔══╝ ██║ ╚██████╔╝██╔╝ ██╗ ╚██████╔╝██║ ██║██║ ╚═╝ ██║███████╗ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; interface IFoxGameNFT { enum Kind { RABBIT, FOX, HUNTER } struct Traits { Kind kind; uint8 advantage; uint8[7] traits; } function getMaxGEN0Players() external pure returns (uint16); function getTraits(uint16) external view returns (Traits memory); function ownerOf(uint256) external view returns (address owner); function transferFrom(address, address, uint256) external; function safeTransferFrom(address, address, uint256, bytes memory) external; } // 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; } }
* Generates an array composed of all the individual traits and values @param tokenId the ID of the token to compose the metadata for @return traits JSON array of all of the attributes for given token ID/
function _compileAttributes(uint16 tokenId, IFoxGameNFT.Traits memory t) internal view returns (string memory traits) { if (t.kind == IFoxGameNFT.Kind.RABBIT) { traits = string(abi.encodePacked( _attributeForTypeAndValue("Fur", traitData[0][t.traits[0]].name), ",", _attributeForTypeAndValue("Paws", traitData[1][t.traits[1]].name), ",", _attributeForTypeAndValue("Mouth", traitData[2][t.traits[2]].name), ",", _attributeForTypeAndValue("Nose", traitData[3][t.traits[3]].name), ",", _attributeForTypeAndValue("Eyes", traitData[4][t.traits[4]].name), ",", _attributeForTypeAndValue("Ears", traitData[5][t.traits[5]].name), ",", _attributeForTypeAndValue("Head", traitData[6][t.traits[6]].name), "," )); traits = string(abi.encodePacked( _attributeForTypeAndValue("Tail", traitData[7][t.traits[0]].name), ",", _attributeForTypeAndValue("Fur", traitData[8][t.traits[1]].name), ",", _attributeForTypeAndValue("Feet", traitData[9][t.traits[2]].name), ",", _attributeForTypeAndValue("Neck", traitData[10][t.traits[3]].name), ",", _attributeForTypeAndValue("Mouth", traitData[11][t.traits[4]].name), ",", _attributeForTypeAndValue("Eyes", traitData[12][t.traits[5]].name), ",", _attributeForTypeAndValue("Cunning Score", _advantages[t.advantage]), "," )); traits = string(abi.encodePacked( _attributeForTypeAndValue("Clothes", traitData[13][t.traits[0]].name), ",", _attributeForTypeAndValue("Marksman", traitData[14][t.traits[1]].name), ",", _attributeForTypeAndValue("Neck", traitData[15][t.traits[2]].name), ",", _attributeForTypeAndValue("Mouth", traitData[16][t.traits[3]].name), ",", _attributeForTypeAndValue("Eyes", traitData[17][t.traits[4]].name), ",", _attributeForTypeAndValue("Hat", traitData[18][t.traits[5]].name), ",", _attributeForTypeAndValue("Marksman Score", _advantages[t.advantage]), "," )); } return string(abi.encodePacked( '[', traits, '{"trait_type":"Generation","value":', tokenId <= foxNFT.getMaxGEN0Players() ? '"GEN 0"' : '"GEN 1"', '}]' )); }
1,272,983
[ 1, 6653, 392, 526, 18673, 434, 777, 326, 7327, 18370, 471, 924, 225, 1147, 548, 326, 1599, 434, 326, 1147, 358, 11458, 326, 1982, 364, 327, 18370, 1796, 526, 434, 777, 434, 326, 1677, 364, 864, 1147, 1599, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 389, 11100, 2498, 12, 11890, 2313, 1147, 548, 16, 11083, 2409, 12496, 50, 4464, 18, 30370, 3778, 268, 13, 2713, 1476, 1135, 261, 1080, 3778, 18370, 13, 288, 203, 565, 309, 261, 88, 18, 9224, 422, 11083, 2409, 12496, 50, 4464, 18, 5677, 18, 54, 2090, 15650, 13, 288, 203, 1377, 18370, 273, 533, 12, 21457, 18, 3015, 4420, 329, 12, 203, 3639, 389, 4589, 22405, 30154, 2932, 42, 295, 3113, 282, 13517, 751, 63, 20, 6362, 88, 18, 2033, 1282, 63, 20, 65, 8009, 529, 3631, 3104, 3113, 203, 3639, 389, 4589, 22405, 30154, 2932, 52, 6850, 3113, 225, 13517, 751, 63, 21, 6362, 88, 18, 2033, 1282, 63, 21, 65, 8009, 529, 3631, 3104, 3113, 203, 3639, 389, 4589, 22405, 30154, 2932, 49, 15347, 3113, 13517, 751, 63, 22, 6362, 88, 18, 2033, 1282, 63, 22, 65, 8009, 529, 3631, 3104, 3113, 203, 3639, 389, 4589, 22405, 30154, 2932, 2279, 307, 3113, 225, 13517, 751, 63, 23, 6362, 88, 18, 2033, 1282, 63, 23, 65, 8009, 529, 3631, 3104, 3113, 203, 3639, 389, 4589, 22405, 30154, 2932, 41, 9707, 3113, 225, 13517, 751, 63, 24, 6362, 88, 18, 2033, 1282, 63, 24, 65, 8009, 529, 3631, 3104, 3113, 203, 3639, 389, 4589, 22405, 30154, 2932, 41, 5913, 3113, 225, 13517, 751, 63, 25, 6362, 88, 18, 2033, 1282, 63, 25, 65, 8009, 529, 3631, 3104, 3113, 203, 3639, 389, 4589, 22405, 30154, 2932, 1414, 3113, 225, 13517, 751, 63, 26, 6362, 88, 18, 2033, 1282, 63, 26, 65, 8009, 529, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Object is ERC721Enumerable, ReentrancyGuard, Ownable { string[] private power = [ "10", "20", "30", "40", "50", "60", "70", "80", "90", "100" ]; string[] private luck = [ "10", "20", "30", "40", "50", "60", "70", "80", "90", "100" ]; // Cooldown (weeks) string[] private cooldown = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ]; string[] private affinity = [ "Red", "Yellow", "Green", "Blue", "Violet" ]; string[] private sigil = [ "Wolf", "Lion", "Eagle", "Stag", "Bear" ]; string[] private levels = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ]; // Activation Time (days) string[] private activation = [ "1", "2", "3", "4", "5" ]; // Volume string[] private volume = [ "10", "20", "30", "40", "50", "60", "70", "80", "90", "100" ]; function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getPower(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "POWER", power); } function getLuck(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "LUCK", luck); } function getCooldown(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "COOLDOWN", cooldown); } function getAffinity(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "AFFINITY", affinity); } function getSigil(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "SIGIL", sigil); } function getLevels(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "LEVELS", levels); } function getActivation(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "ACTIVATION", activation); } function getVolume(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "VOLUME", volume); } function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId), msg.sender, tx.gasprice))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function tokenURI(uint256 tokenId) override public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: "Helvetica"; font-size: 16px; }</style><defs><radialGradient id="RadialGradient2" cx="-0.1" cy="-0.1" r="0.85"><stop offset="50%" stop-color="purple"/><stop offset="100%" stop-color="black"/></radialGradient></defs>><rect width="100%" height="100%" fill="url(#RadialGradient2)"/><text x="20" y="30" class="base">Power - '; parts[1] = getPower(tokenId); parts[2] = '</text><text x="20" y="50" class="base">Luck - '; parts[3] = getLuck(tokenId); parts[4] = '</text><text x="20" y="70" class="base">Cooldown - '; parts[5] = getCooldown(tokenId); parts[6] = ' week(s)</text><text x="20" y="90" class="base">Affinity - '; parts[7] = getAffinity(tokenId); parts[8] = '</text><text x="20" y="110" class="base">Sigil - '; parts[9] = getSigil(tokenId); parts[10] = '</text><text x="20" y="130" class="base">Levels - '; parts[11] = getLevels(tokenId); parts[12] = '</text><text x="20" y="150" class="base">Activation - '; parts[13] = getActivation(tokenId); parts[14] = ' day(s)</text><text x="20" y="170" class="base">Volume - '; parts[15] = getVolume(tokenId); parts[16] = '</text><text x="132" y="275" class="base" style="font-size: 10px; letter-spacing: 1.5; fill: purple">The Alchemist\'s</text><text x="117" y="300" class="base" style="font-size: 20px; letter-spacing: 5;">GLIMMER</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16])); // attributes: [{"trait_type": "Power", "value": "', getWeapon(tokenId), '"}, {"trait_type": "Luck", "value": "', getChest(tokenId), '"}, {"trait_type": "Cooldown", "value": "', getHead(tokenId), '"}, {"trait_type": "Affinity", "value": "', getWaist(tokenId), '"}, {"trait_type": "Sign", "value": "', getFoot(tokenId), '"}, {"trait_type": "Levels", "value": "', getHand(tokenId), '"}, {"trait_type": "Activation", "value": "', getNeck(tokenId), '"}, {"trait_type": "Charge", "value": "', getRing(tokenId), '"}] string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Object #', toString(tokenId), '", "description": "Why hello there, Moon Boy. It seems that you have found my Glimmer.", "external_url": "https://www.ritualmill.com/", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } function claim(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 5778, "Token ID invalid"); _safeMint(_msgSender(), tokenId); } function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 5777 && tokenId < 6001, "Token ID invalid"); _safeMint(owner(), tokenId); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } constructor() ERC721("Digital Object", "OBJECT") Ownable() {} } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
www.ritualmill.com/", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Object #', toString(tokenId), '", "description": "Why hello there, Moon Boy. It seems that you have found my Glimmer.", "external_url": "https:
9,837,593
[ 1, 5591, 18, 583, 1462, 81, 737, 18, 832, 19, 3113, 315, 2730, 6877, 315, 892, 30, 2730, 19, 11451, 15, 2902, 31, 1969, 1105, 16, 2187, 3360, 1105, 18, 3015, 12, 3890, 12, 2844, 13, 3631, 2119, 1713, 3719, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 533, 3778, 1163, 273, 3360, 1105, 18, 3015, 12, 3890, 12, 1080, 12, 21457, 18, 3015, 4420, 329, 2668, 16711, 529, 6877, 315, 921, 468, 2187, 1762, 12, 2316, 548, 3631, 19197, 315, 3384, 6877, 315, 2888, 93, 19439, 1915, 16, 14987, 265, 605, 13372, 18, 2597, 12001, 716, 1846, 1240, 1392, 3399, 611, 7091, 6592, 1199, 16, 315, 9375, 67, 718, 6877, 315, 4528, 30, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.7; // SPDX-License-Identifier: MIT import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeEIP20.sol"; import "./Ownable.sol"; import "./Pausable.sol"; import "./Lockable.sol"; /** * @title StakePool * @notice Implements a Ownable, Pausable, Lockable, ReentrancyGuard */ contract StakePool is Ownable, Pausable, Lockable, ReentrancyGuard { using SafeMath for uint256; using SafeEIP20 for IEIP20; // We usually require to know who are all the stakeholders. address[] internal stakeholders; string[] internal poollist; uint256 internal currentTimestamp = block.timestamp; struct Stake { uint256 amount; // The stake amount uint256 duration; // The duration in weeks of how long the stake should be locked from unstaking address referral; // The affiliate address string pool; // The selected pool uint256 reward; // The staking reward earned uint256 reward_paid; // The staking reward paid out so far uint256 reward_count; // The total amount of times a reward has been distributed uint256 reward_claimable_after_duration; // The duration in weeks after which a reward can be withdrawn uint256 bonus; // The referral bonus earned uint256 bonus_paid; // The referral bonus paid out so far uint256 bonus_claimable_after_duration; // The duration in weeks after which a bonus can be withdrawn uint256 bonus_updated_at; // The last time a bonus is updated uint256 reward_updated_at; // The last time a staking reward is updated uint256 bonus_last_withdraw_at; // The last time a bonus is withrawn uint256 reward_last_withdraw_at; // The last time a staking reward is withrawn uint256 last_withdraw_at; // The last time a stake is withrawn uint256 created_at; // Timestamp of when stake was created uint256 updated_at; // Timestamp of when stake was last modified bool valid; // If a stake is valid or not } struct Pool { string name; // The name of the pool, should be a single word in lowercase address staking_token; // The staking token address address reward_token; // The staking reward token address address bonus_token; // The bonus token address uint256 duration_in_weeks; // The duration in weeks of the pool uint256 reward_percentage; // The reward percentage of the pool uint256 minimum_stake; // The minimum amount a stakeholder can stake uint256 reward_halving; // Will halve reward every 2 year untill the 6th year if activated uint256 referral_bonus_percentage; // The referral bonus percentage of the pool uint256 reward_claimable_after_duration; // The duration in weeks after which a reward can be withdrawn uint256 bonus_claimable_after_duration; // The duration in weeks after which a bonus can be withdrawn address default_referral; // The default referral address of the pool uint256 created_at; // Timestamp of when pool was created uint256 updated_at; // Timestamp of when pool was last modified bool valid; // If a pool is valid or not } //The stakes for each stakeholder. mapping(address => Stake) internal stakes; //The pools for each poollist. mapping(string => Pool) internal pools; mapping(address => uint256) private _balances; uint256 private _totalSupply; uint256 public balance; constructor() { } receive() payable external { balance += msg.value; emit TransferReceived(_msgSender(), msg.value); } function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /* ========== STAKES METHODS ---------- /** * @notice A method for a stakeholder to create a stake. * @param amount The size of the stake to be created. * @param _pool The pool to stake in. * @param _affiliate An affiliate address to benefit from the stake. */ function createStake(uint256 amount, string memory _pool, address _affiliate) external nonReentrant whenNotPaused whenNotLocked { require(amount > 0, "Insufficient stake amount"); Stake storage stake = stakes[_msgSender()]; if (!stake.valid) { _isValidPool(_pool); Pool memory pool = pools[_pool]; require(pool.valid, "Invalid pool"); require(amount >= pool.minimum_stake, "Stake is below minimum allowed stake"); _totalSupply = _totalSupply.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); IEIP20(pool.staking_token).safeTransferFrom(_msgSender(), address(this), amount); addStakeholder(_msgSender()); stake.amount = stake.amount.add(amount); stake.pool = _pool; stake.duration = pool.duration_in_weeks; stake.reward_claimable_after_duration = pool.reward_claimable_after_duration; stake.bonus_claimable_after_duration = pool.bonus_claimable_after_duration; stake.created_at = currentTimestamp; stake.updated_at = currentTimestamp; stake.valid = true; stake.reward = stake.reward.add(0); stake.reward_count = 0; stake.bonus = stake.bonus.add(0); address _referral_address = pool.default_referral; //check if the referral is a stakeholder and also if _msgSender is not the referral (bool _isReferralStakeholder,) = isStakeholder(_affiliate); if (_isReferralStakeholder && _msgSender() != _affiliate){ _referral_address = _affiliate; } uint256 referral_bonus = amount / (100 * (10 ** 18)); uint256 affiliate_bonus = referral_bonus.mul(pool.referral_bonus_percentage); stake.referral = _referral_address; Stake storage referral_stake = stakes[_referral_address]; referral_stake.bonus = referral_stake.bonus.add(affiliate_bonus); emit Staked(_msgSender(), amount, pool.name); }else{ Pool memory pool = pools[stake.pool]; require(pool.valid, "Invalid pool"); _totalSupply = _totalSupply.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); IEIP20(pool.staking_token).safeTransferFrom(_msgSender(), address(this), amount); stake.amount = stake.amount.add(amount); stake.updated_at = currentTimestamp; emit Staked(_msgSender(), amount, pool.name); } } /** * @notice A method for a stakeholder to remove a stake. * @param amount The size of the stake to be removed. */ function withdraw(uint256 amount) public nonReentrant whenNotPaused whenNotLocked { require(amount > 0, "Cannot withdraw 0"); Stake storage stake = stakes[_msgSender()]; require(stake.valid, "No stake found."); Pool memory pool = pools[stake.pool]; require(pool.valid, "Invalid pool"); require(_isExpired(stake.created_at, stake.duration), "You can't withdraw untill the stake duration is over."); require(stake.amount >= amount, "Insufficient amount of stakes"); stake.amount = stake.amount.sub(amount); if (stake.amount == 0) removeStakeholder(_msgSender()); _totalSupply = _totalSupply.sub(amount); _balances[_msgSender()] = _balances[_msgSender()].sub(amount); IEIP20(pool.staking_token).safeTransfer(_msgSender(), amount); emit Withdrawn(_msgSender(), amount, stake.pool); } /** * @notice A method to retrieve the stake for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return uint256 The amount of wei staked. */ function stakeOf(address _stakeholder) public view returns (uint256, string memory) { require(_stakeholder != address(0), "Invalid stakeholder"); Stake memory stake = stakes[_stakeholder]; require(stake.valid, "No stake found."); return (stake.amount,stake.pool); } /** * @notice A method to the aggregated stakes from all stakeholders. * @return uint256 The aggregated stakes from all stakeholders. */ function totalStakes() public view returns (uint256) { uint256 _totalStakes = 0; for (uint256 s = 0; s < stakeholders.length; s += 1) { Stake memory stake = stakes[stakeholders[s]]; _totalStakes = _totalStakes.add(stake.amount); } return _totalStakes; } /** * @notice A method to check if an address is a stakeholder. * @param _address The address to verify. * @return bool, uint256 Whether the address is a stakeholder, * and if so its position in the stakeholders array. */ function isStakeholder(address _address) public view returns (bool, uint256) { for (uint256 s = 0; s < stakeholders.length; s += 1) { if (_address == stakeholders[s]) return (true, s); } return (false, 0); } function exit() external { withdraw(_balances[_msgSender()]); getReward(); getBonus(); } /* ========== REWARD METHODS ========== */ /** * @notice A method to allow a stakeholder to check his rewards. * @param _stakeholder The stakeholder to check rewards for. */ function rewardOf(address _stakeholder) public view returns (uint256) { Stake memory stake = stakes[_stakeholder]; return stake.reward; } /** * @notice A method to the aggregated rewards from all stakeholders. * @return uint256 The aggregated rewards from all stakeholders. */ function totalRewards() public view returns (uint256) { uint256 _totalRewards = 0; for (uint256 s = 0; s < stakeholders.length; s += 1) { address stakeholder = stakeholders[s]; Stake memory stake = stakes[stakeholder]; _totalRewards = _totalRewards.add(stake.reward); } return _totalRewards; } function calculateTotalHalvedReward(address _stakeholder) public view returns (uint256) { require(_stakeholder != address(0), "Invalid stakeholder"); Stake memory stake = stakes[_stakeholder]; require(stake.valid, "Stake not found"); Pool memory pool = pools[stake.pool]; require(pool.valid, "Invalid pool"); uint256 reward = stake.amount / (100 * (10 ** 18)); uint256 total_reward = reward.mul(pool.reward_percentage); uint256 total_halved_reward = total_reward; if(pool.reward_halving > 0){ if (block.timestamp >= pool.created_at + 104 weeks) { total_halved_reward = total_reward/2; if(block.timestamp >= pool.created_at + 208 weeks){ total_halved_reward = total_reward/4; if(block.timestamp >= pool.created_at + 312 weeks){ total_halved_reward = total_reward; } } } } return total_halved_reward; } /** * @notice A simple method that calculates the total rewards for each stakeholder. * @param _stakeholder The stakeholder to calculate rewards for. */ function calculateTotalReward(address _stakeholder) public view returns (uint256) { require(_stakeholder != address(0), "Invalid stakeholder"); Stake memory stake = stakes[_stakeholder]; require(stake.valid, "Stake not found"); Pool memory pool = pools[stake.pool]; require(pool.valid, "Invalid pool"); return calculateTotalHalvedReward(_stakeholder); } /** * @notice A simple method that calculates the weekly rewards for each stakeholder. * @param _stakeholder The stakeholder to calculate rewards for. */ function calculateWeeklyReward(address _stakeholder) public view returns (uint256) { require(_stakeholder != address(0), "Invalid stakeholder"); Stake memory stake = stakes[_stakeholder]; require(stake.valid, "Stake not found"); Pool memory pool = pools[stake.pool]; require(pool.valid, "Invalid pool"); uint256 total_reward = calculateTotalReward(_stakeholder); uint256 weekly_reward = total_reward / pool.duration_in_weeks; return weekly_reward; } /** * @notice A simple method that calculates the daily rewards for each stakeholder. * @param _stakeholder The stakeholder to calculate rewards for. */ function calculateDailyReward(address _stakeholder) public view returns (uint256) { require(_stakeholder != address(0), "Invalid stakeholder"); Stake memory stake = stakes[_stakeholder]; require(stake.valid, "Stake not found"); Pool memory pool = pools[stake.pool]; require(pool.valid, "Invalid pool"); uint256 weekly_reward = calculateWeeklyReward(_stakeholder); uint256 daily_reward = weekly_reward / 7; return daily_reward; } /** * @notice A method to distribute total rewards to all stakeholders. */ function distributeTotalRewards() public payable onlyOwner { uint256 _totalRewards = 0; for (uint256 s = 0; s < stakeholders.length; s += 1) { address stakeholder = stakeholders[s]; Stake storage stake = stakes[stakeholder]; if(stake.valid){ uint256 _reward = calculateTotalReward(stakeholder); uint256 _next_reward_in_days = 7; uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days); if (_reward > stake.reward) { if (stake.reward_count < _max_reward_count) { stake.reward = _reward; stake.reward_count = stake.reward_count.add(_max_reward_count); stake.reward_updated_at = currentTimestamp; _totalRewards = _totalRewards.add(_reward); } } } } emit TotalRewardDistributed(_totalRewards); } /** * @notice A method to distribute weekly rewards to all stakeholders. */ function distributeWeeklyRewards() public payable onlyOwner { uint256 _totalRewards = 0; for (uint256 s = 0; s < stakeholders.length; s += 1) { address stakeholder = stakeholders[s]; Stake storage stake = stakes[stakeholder]; if(stake.valid){ uint256 _total_reward = calculateTotalReward(stakeholder); uint256 _reward = calculateWeeklyReward(stakeholder); uint256 _next_reward_in_days = 7; uint256 _check_reward_count_exceeded = stake.reward_count + _next_reward_in_days; uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days); //check if staking period for stakeholder has not expired if (!_isExpired(stake.created_at, stake.duration)) { if (stake.reward_count < _max_reward_count && _check_reward_count_exceeded <= _max_reward_count && _isExpiredInDays(stake.reward_updated_at, _next_reward_in_days) && _total_reward > stake.reward) { stake.reward = stake.reward.add(_reward); stake.reward_count = stake.reward_count.add(_next_reward_in_days); stake.reward_updated_at = currentTimestamp; _totalRewards = _totalRewards.add(_reward); } } } } emit WeeklyRewardDistributed(_totalRewards); } /** * @notice A method to distribute daily rewards to all stakeholders. */ function distributeDailyRewards() public payable onlyOwner { uint256 _totalRewards = 0; for (uint256 s = 0; s < stakeholders.length; s += 1) { address stakeholder = stakeholders[s]; Stake storage stake = stakes[stakeholder]; if(stake.valid){ uint256 _total_reward = calculateTotalReward(stakeholder); uint256 _reward = calculateDailyReward(stakeholder); uint256 _next_reward_in_days = 1; uint256 _check_reward_count_exceeded = stake.reward_count + _next_reward_in_days; uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days); //check if staking period for stakeholder has not expired if (!_isExpired(stake.created_at, stake.duration)) { if (stake.reward_count < _max_reward_count && _check_reward_count_exceeded <= _max_reward_count && _isExpiredInDays(stake.reward_updated_at, _next_reward_in_days) && _total_reward > stake.reward) { stake.reward = stake.reward.add(_reward); stake.reward_count = stake.reward_count.add(_next_reward_in_days); stake.reward_updated_at = currentTimestamp; _totalRewards = _totalRewards.add(_reward); } } } } emit DailyRewardDistributed(_totalRewards); } /** * @notice A method to allow a stakeholder to withdraw his rewards. */ function getReward() public nonReentrant whenNotPaused whenNotLocked { Stake storage stake = stakes[_msgSender()]; require(stake.valid, "No stake found."); require(_isExpired(stake.created_at, stake.reward_claimable_after_duration), "Can't withdraw reward until the holding duration is over."); Pool memory pool = pools[stake.pool]; require(pool.valid, "Invalid pool"); uint256 _reward = stake.reward; if (_reward > 0) { IEIP20(pool.reward_token).safeTransfer(_msgSender(), _reward); stake.reward = 0; //reset amount stake.reward_count = 0; //reset count stake.reward_last_withdraw_at = currentTimestamp; stake.reward_paid = stake.reward_paid.add(_reward); emit RewardPaid(_msgSender(), _reward); } } /* ========== REFERRAL BONUS METHODS ========== */ /** * @notice A method to allow a stakeholder to check his bonus. * @param _stakeholder The stakeholder to check bonus for. */ function bonusOf(address _stakeholder) public view returns (uint256) { Stake memory stake = stakes[_stakeholder]; return stake.bonus; } /** * @notice A method to the aggregated bonuses from all stakeholders. * @return uint256 The aggregated bonuses from all stakeholders. */ function totalBonuses() public view returns (uint256) { uint256 _totalBonuses = 0; for (uint256 s = 0; s < stakeholders.length; s += 1) { address stakeholder = stakeholders[s]; Stake memory stake = stakes[stakeholder]; _totalBonuses = _totalBonuses.add(stake.bonus); } return _totalBonuses; } /** * @notice A method to allow a stakeholder to withdraw his bonus. */ function getBonus() public nonReentrant whenNotPaused whenNotLocked { Stake storage stake = stakes[_msgSender()]; require(stake.valid, "No stake found."); require(_isExpired(stake.created_at, stake.bonus_claimable_after_duration), "Can't withdraw reward until the holding duration is over."); Pool memory pool = pools[stake.pool]; require(pool.valid, "Invalid pool"); uint256 _bonus = stake.bonus; if (_bonus > 0) { IEIP20(pool.bonus_token).safeTransfer(_msgSender(), _bonus); stake.bonus = 0; //reset amount stake.bonus_last_withdraw_at = currentTimestamp; stake.bonus_paid = stake.bonus_paid.add(_bonus); emit BonusPaid(_msgSender(), _bonus); } } /* ========== POOL METHODS ========== */ /** * @notice A method for a contract owner to create a staking pool. * @param _name The name of the pool to be created. * @param _minimum_stake The minimum a stakeholder can stake. * @param _duration The duration in weeks of the pool to be created. * @param _reward_percentage The total reward percentage of the pool to be created * @param _reward_halving Whether to activate reward halving or not. 1 to activate | 0 to deactivate * @param _referral_bonus_percentage The referral bonus percentage of the pool to be created * @param _default_referral The default affiliate address if none is set * @param _reward_claimable_after When the reward will be claimable after specified weeks * @param _bonus_claimable_after When the bonus will be claimable after specified weeks * @param _staking_token The staking token contract address * @param _reward_token The reward token contract address * @param _bonus_token The bonus token contract address */ function createPool(string memory _name, uint256 _minimum_stake, uint256 _duration, uint256 _reward_percentage, uint256 _reward_halving, uint256 _referral_bonus_percentage, address _default_referral, uint256 _reward_claimable_after, uint256 _bonus_claimable_after, address _staking_token, address _reward_token, address _bonus_token) public onlyOwner { require(_duration > 0, "Duration in weeks can't be zero"); require(_minimum_stake > 0, "Minimum stake can't be zero"); require(_reward_percentage > 0, "Total reward percentage can't be zero"); Pool storage pool = pools[_name]; if (!pool.valid) { _addPool(_name); pool.name = _name; pool.minimum_stake = _minimum_stake; pool.duration_in_weeks = _duration; pool.reward_percentage = _reward_percentage; pool.reward_halving = (_reward_halving > 0)? 1 : 0; pool.referral_bonus_percentage = _referral_bonus_percentage; pool.default_referral = _default_referral; pool.reward_claimable_after_duration = _reward_claimable_after; pool.bonus_claimable_after_duration = _bonus_claimable_after; pool.staking_token = _staking_token; pool.reward_token = _reward_token; pool.bonus_token = _bonus_token; pool.created_at = currentTimestamp; pool.valid = true; } emit PoolAdded(pool.name, _duration); } /** * @notice A method for a contract owner to update a staking pool. * @param _name The name of the pool to be updated. * @param _minimum_stake The minimum a stakeholder can stake. * @param _duration The duration in weeks of the pool to be created. * @param _reward_percentage The reward percentage of the pool to be created * @param _reward_halving Whether to activate reward halving or not. 1 to activate | 0 to deactivate * @param _referral_bonus_percentage The referral bonus percentage of the pool to be created * @param _default_referral The default affiliate address if none is set * @param _reward_claimable_after When the reward will be claimable after specified weeks * @param _bonus_claimable_after When the bonus will be claimable after specified weeks * @param _staking_token The staking token contract address * @param _reward_token The reward token contract address * @param _bonus_token The bonus token contract address */ function updatePool(string memory _name, uint256 _minimum_stake, uint256 _duration, uint256 _reward_percentage, uint256 _reward_halving, uint256 _referral_bonus_percentage, address _default_referral, uint256 _reward_claimable_after, uint256 _bonus_claimable_after, address _staking_token, address _reward_token, address _bonus_token) public onlyOwner { require(_duration > 0, "Duration in weeks can't be zero"); require(_minimum_stake > 0, "Minimum stake can't be zero"); require(_reward_percentage > 0, "Total reward percentage can't be zero"); Pool storage pool = pools[_name]; require(pool.valid, "No pool found."); pool.name = _name; pool.minimum_stake = _minimum_stake; pool.duration_in_weeks = _duration; pool.reward_percentage = _reward_percentage; pool.reward_halving = (_reward_halving > 0)? 1 : 0; pool.referral_bonus_percentage = _referral_bonus_percentage; pool.default_referral = _default_referral; pool.reward_claimable_after_duration = _reward_claimable_after; pool.bonus_claimable_after_duration = _bonus_claimable_after; pool.staking_token = _staking_token; pool.reward_token = _reward_token; pool.bonus_token = _bonus_token; pool.updated_at = currentTimestamp; emit PoolUpdated(pool.name, _duration); } /** * @notice A method for a contract owner to remove a staking pool. * @param _name The name of the pool to be removed. */ function removePool(string memory _name) public onlyOwner { Pool storage pool = pools[_name]; require(pool.valid, "No pool found."); (bool _isPool, uint256 s) = isPool(_name); if (_isPool) { //revert stakeholders stakes before removing the pool for (uint256 i = 0; i < stakeholders.length; i += 1) { address _stakeholder = stakeholders[i]; Stake storage stake = stakes[_stakeholder]; uint256 _stake = stake.amount; stake.amount = stake.amount.sub(_stake); if (stake.amount == 0) removeStakeholder(_stakeholder); _totalSupply = _totalSupply.sub(_stake); _balances[_stakeholder] = _balances[_stakeholder].sub(_stake); IEIP20(pool.staking_token).safeTransfer(_stakeholder, _stake); } delete pools[_name]; poollist[s] = poollist[poollist.length - 1]; poollist.pop(); emit PoolDeleted(pool.name); } } /** * @notice A method to retrieve the pool with the name. * @param _name The pool to retrieve */ function poolOf(string memory _name) public view returns (string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, address, address){ Pool memory pool = pools[_name]; require(pool.valid, "No pool found."); return (pool.name, pool.minimum_stake, pool.duration_in_weeks, pool.reward_percentage, pool.reward_halving,pool.referral_bonus_percentage, pool.reward_claimable_after_duration, pool.bonus_claimable_after_duration, pool.staking_token,pool.reward_token,pool.bonus_token); } function poolStakes(string memory _pool) public view returns (uint256) { uint256 _totalStakes = 0; for (uint256 s = 0; s < stakeholders.length; s += 1) { Stake memory stake = stakes[stakeholders[s]]; if(_compareStrings(stake.pool,_pool)){ _totalStakes = _totalStakes.add(stake.amount); } } return _totalStakes; } /** * @notice A method to check if a pool exist. * @param _name The name to verify. * @return bool, uint256 Whether the name exist, * and if so its position in the poollist array. */ function isPool(string memory _name) public view returns (bool, uint256) { for (uint256 s = 0; s < poollist.length; s += 1) { if (_compareStrings(_name,poollist[s])) return (true, s); } return (false, 0); } /* ========== UTILS METHODS ========== */ function withdrawNative(uint amount, address payable destAddr) public onlyOwner { require(amount <= balance, "Insufficient funds"); destAddr.transfer(amount); balance -= amount; emit TransferSent(_msgSender(), destAddr, amount); } function transferToken(address token, address to, uint256 amount) public onlyOwner { uint256 EIP20balance = IEIP20(token).balanceOf(address(this)); require(amount <= EIP20balance, "balance is low"); IEIP20(token).safeTransfer(to, amount); emit TransferSent(_msgSender(), to, amount); } function balanceOfToken(address token) public view returns (uint256) { uint256 tokenBal = IEIP20(token).balanceOf(address(this)); return tokenBal; } function balanceOfNative() public view returns (uint256) { uint256 nativeBal = address(this).balance; return nativeBal; } /* ========== INTERNAL METHODS ========== */ /** * @notice A method to add a stakeholder. * @param _stakeholder The stakeholder to add. */ function addStakeholder(address _stakeholder) internal { (bool _isStakeholder,) = isStakeholder(_stakeholder); if (!_isStakeholder) stakeholders.push(_stakeholder); } /** * @notice A method to remove a stakeholder. * @param _stakeholder The stakeholder to remove. */ function removeStakeholder(address _stakeholder) internal { (bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder); if (_isStakeholder) { stakeholders[s] = stakeholders[stakeholders.length - 1]; stakeholders.pop(); Stake storage stake = stakes[_stakeholder]; stake.valid = false; } } /** * @notice A method to add a pool. * @param _name The name to add. */ function _addPool(string memory _name) internal { (bool _isPool,) = isPool(_name); if (!_isPool) poollist.push(_name); } function _isValidPool (string memory _pool) internal view { (bool _isPool, ) = isPool(_pool); require(_isPool, "Invalid stake pool"); } function _compareStrings(string memory _a, string memory _b) internal pure returns (bool) { return (keccak256(bytes(_a)) == keccak256(bytes(_b))); } function _toLower(string memory str) internal pure returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character... if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { // So we add 32 to make it lowercase bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } function _isExpired(uint256 _time, uint256 _duration) internal view returns(bool){ if (block.timestamp >= _time + _duration * 1 weeks) { return true; } else { return false; } } function _isExpiredInDays(uint256 _time, uint256 _duration) internal view returns(bool){ if (block.timestamp >= _time + _duration * 1 days) { return true; } else { return false; } } /* ========== EVENTS ========== */ event Staked(address indexed sender, uint256 amount, string pool); event Withdrawn(address indexed sender, uint256 amount, string pool); event RewardPaid(address indexed user, uint256 reward); event DailyRewardDistributed(uint256 reward); event WeeklyRewardDistributed(uint256 reward); event TotalRewardDistributed(uint256 reward); event BonusPaid(address indexed user, uint256 bonus); event PoolAdded(string pool, uint256 duration); event PoolUpdated(string pool, uint256 duration); event PoolDeleted(string pool); event TransferReceived(address _from, uint _amount); event TransferSent(address _from, address _destAddr, uint _amount); }
* @notice A method to distribute daily rewards to all stakeholders./check if staking period for stakeholder has not expired
function distributeDailyRewards() public payable onlyOwner { uint256 _totalRewards = 0; for (uint256 s = 0; s < stakeholders.length; s += 1) { address stakeholder = stakeholders[s]; Stake storage stake = stakes[stakeholder]; if(stake.valid){ uint256 _total_reward = calculateTotalReward(stakeholder); uint256 _reward = calculateDailyReward(stakeholder); uint256 _next_reward_in_days = 1; uint256 _check_reward_count_exceeded = stake.reward_count + _next_reward_in_days; uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days); if (!_isExpired(stake.created_at, stake.duration)) { if (stake.reward_count < _max_reward_count && _check_reward_count_exceeded <= _max_reward_count && _isExpiredInDays(stake.reward_updated_at, _next_reward_in_days) && _total_reward > stake.reward) { stake.reward = stake.reward.add(_reward); stake.reward_count = stake.reward_count.add(_next_reward_in_days); stake.reward_updated_at = currentTimestamp; _totalRewards = _totalRewards.add(_reward); } } } } emit DailyRewardDistributed(_totalRewards); }
927,693
[ 1, 37, 707, 358, 25722, 18872, 283, 6397, 358, 777, 384, 911, 9000, 18, 19, 1893, 309, 384, 6159, 3879, 364, 384, 911, 4505, 711, 486, 7708, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25722, 40, 12857, 17631, 14727, 1435, 1071, 8843, 429, 1338, 5541, 288, 203, 203, 3639, 2254, 5034, 389, 4963, 17631, 14727, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 5034, 272, 273, 374, 31, 272, 411, 384, 911, 9000, 18, 2469, 31, 272, 1011, 404, 13, 288, 203, 203, 5411, 1758, 384, 911, 4505, 273, 384, 911, 9000, 63, 87, 15533, 203, 203, 5411, 934, 911, 2502, 384, 911, 273, 384, 3223, 63, 334, 911, 4505, 15533, 203, 203, 5411, 309, 12, 334, 911, 18, 877, 15329, 203, 1171, 203, 7734, 2254, 5034, 389, 4963, 67, 266, 2913, 273, 4604, 5269, 17631, 1060, 12, 334, 911, 4505, 1769, 203, 1171, 203, 7734, 2254, 5034, 389, 266, 2913, 273, 4604, 40, 12857, 17631, 1060, 12, 334, 911, 4505, 1769, 203, 203, 7734, 2254, 5034, 389, 4285, 67, 266, 2913, 67, 267, 67, 9810, 273, 404, 31, 203, 1171, 203, 7734, 2254, 5034, 389, 1893, 67, 266, 2913, 67, 1883, 67, 338, 5816, 273, 384, 911, 18, 266, 2913, 67, 1883, 397, 389, 4285, 67, 266, 2913, 67, 267, 67, 9810, 31, 203, 1171, 203, 7734, 2254, 5034, 389, 1896, 67, 266, 2913, 67, 1883, 273, 384, 911, 18, 8760, 18, 16411, 24899, 4285, 67, 266, 2913, 67, 267, 67, 9810, 1769, 203, 1171, 203, 7734, 309, 16051, 67, 291, 10556, 12, 334, 911, 18, 4824, 67, 270, 16, 384, 911, 18, 8760, 3719, 288, 203, 10792, 309, 261, 334, 911, 18, 266, 2913, 67, 1883, 411, 389, 1896, 67, 266, 2913, 67, 2 ]
/* * Copyright 2020 ConsenSys Software 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-2.0 */ pragma solidity >=0.7.1; /** * Signature verification for ECDSA / KECCAK256 using secp256k1 curve. */ contract EcdsaSignatureVerification { /** * Verify a signature. * * @param _signer Address that corresponds to the public key of the signer. * @param _message Message to be verified. * @param _signature Signature to be verified. * */ function verify( address _signer, bytes calldata _message, bytes calldata _signature ) internal pure returns (bool) { // Check the signature length if (_signature.length != 65) { return false; } bytes memory sig = _signature; bytes32 r; bytes32 s; uint8 v; // Split the signature into components r, s and v variables with inline assembly. assembly { r := mload(add(sig, 0x20)) s := mload(add(sig, 0x40)) v := byte(0, mload(add(sig, 0x60))) } return verifySigComponents(_signer, _message, r, s, v); } /** * Verify a signature. * * @param _signer Address that corresponds to the public key of the signer. * @param _message Message to be verified. * @param _sigR Component of the signature to be verified. * @param _sigS Component of the signature to be verified. * @param _sigV Component of the signature to be verified. * */ function verifySigComponents( address _signer, bytes calldata _message, bytes32 _sigR, bytes32 _sigS, uint8 _sigV ) internal pure returns (bool) { bytes32 digest = keccak256(_message); if (_sigV != 27 && _sigV != 28) { return false; } else { // The signature is verified if the address recovered from the signature matches // the signer address (which maps to the public key). return _signer == ecrecover(digest, _sigV, _sigR, _sigS); } } }
* Verify a signature. @param _signer Address that corresponds to the public key of the signer. @param _message Message to be verified. @param _signature Signature to be verified./ Check the signature length Split the signature into components r, s and v variables with inline assembly.
) internal pure returns (bool) { if (_signature.length != 65) { return false; } bytes memory sig = _signature; bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 0x20)) s := mload(add(sig, 0x40)) v := byte(0, mload(add(sig, 0x60))) } return verifySigComponents(_signer, _message, r, s, v); }
990,826
[ 1, 8097, 279, 3372, 18, 225, 389, 2977, 264, 5267, 716, 13955, 358, 326, 1071, 498, 434, 326, 10363, 18, 225, 389, 2150, 2350, 358, 506, 13808, 18, 225, 389, 8195, 9249, 358, 506, 13808, 18, 19, 2073, 326, 3372, 769, 5385, 326, 3372, 1368, 4085, 436, 16, 272, 471, 331, 3152, 598, 6370, 19931, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 262, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 67, 8195, 18, 2469, 480, 15892, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 1731, 3778, 3553, 273, 389, 8195, 31, 203, 3639, 1731, 1578, 436, 31, 203, 3639, 1731, 1578, 272, 31, 203, 3639, 2254, 28, 331, 31, 203, 203, 3639, 19931, 288, 203, 5411, 436, 519, 312, 945, 12, 1289, 12, 7340, 16, 374, 92, 3462, 3719, 203, 5411, 272, 519, 312, 945, 12, 1289, 12, 7340, 16, 374, 92, 7132, 3719, 203, 5411, 331, 519, 1160, 12, 20, 16, 312, 945, 12, 1289, 12, 7340, 16, 374, 92, 4848, 20349, 203, 3639, 289, 203, 203, 3639, 327, 3929, 8267, 7171, 24899, 2977, 264, 16, 389, 2150, 16, 436, 16, 272, 16, 331, 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 ]
//Address: 0x095c0f071fd75875a6b5a1def3f3a993f591080c //Contract name: Locker //Balance: 0 Ether //Verification Date: 6/11/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "mul overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "sub underflow"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function roundedDiv(uint a, uint b) internal pure returns (uint256) { require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason uint256 z = a / b; if (a % b >= b / 2) { z++; // no need for safe add b/c it can happen only if we divided the input } return z; } } /* Generic contract to authorise calls to certain functions only from a given address. The address authorised must be a contract (multisig or not, depending on the permission), except for local test deployment works as: 1. contract deployer account deploys contracts 2. constructor grants "PermissionGranter" permission to deployer account 3. deployer account executes initial setup (no multiSig) 4. deployer account grants PermissionGranter permission for the MultiSig contract (e.g. StabilityBoardProxy or PreTokenProxy) 5. deployer account revokes its own PermissionGranter permission */ contract Restricted { // NB: using bytes32 rather than the string type because it's cheaper gas-wise: mapping (address => mapping (bytes32 => bool)) public permissions; event PermissionGranted(address indexed agent, bytes32 grantedPermission); event PermissionRevoked(address indexed agent, bytes32 revokedPermission); modifier restrict(bytes32 requiredPermission) { require(permissions[msg.sender][requiredPermission], "msg.sender must have permission"); _; } constructor(address permissionGranterContract) public { require(permissionGranterContract != address(0), "permissionGranterContract must be set"); permissions[permissionGranterContract]["PermissionGranter"] = true; emit PermissionGranted(permissionGranterContract, "PermissionGranter"); } function grantPermission(address agent, bytes32 requiredPermission) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); permissions[agent][requiredPermission] = true; emit PermissionGranted(agent, requiredPermission); } function grantMultiplePermissions(address agent, bytes32[] requiredPermissions) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); uint256 length = requiredPermissions.length; for (uint256 i = 0; i < length; i++) { grantPermission(agent, requiredPermissions[i]); } } function revokePermission(address agent, bytes32 requiredPermission) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); permissions[agent][requiredPermission] = false; emit PermissionRevoked(agent, requiredPermission); } function revokeMultiplePermissions(address agent, bytes32[] requiredPermissions) public { uint256 length = requiredPermissions.length; for (uint256 i = 0; i < length; i++) { revokePermission(agent, requiredPermissions[i]); } } } /** * @title Eliptic curve signature operations * * @dev Based on https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ECRecovery.sol * * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 * */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * @dev and hash the result */ 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)); } } interface ERC20Interface { event Approval(address indexed _owner, address indexed _spender, uint _value); event Transfer(address indexed from, address indexed to, uint amount); function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name function transferFrom(address from, address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function balanceOf(address who) external view returns (uint); function allowance(address _owner, address _spender) external view returns (uint remaining); } interface TokenReceiver { function transferNotification(address from, uint256 amount, uint data) external; } contract AugmintTokenInterface is Restricted, ERC20Interface { using SafeMath for uint256; string public name; string public symbol; bytes32 public peggedSymbol; uint8 public decimals; uint public totalSupply; mapping(address => uint256) public balances; // Balances for each account mapping(address => mapping (address => uint256)) public allowed; // allowances added with approve() address public stabilityBoardProxy; TransferFeeInterface public feeAccount; mapping(bytes32 => bool) public delegatedTxHashesUsed; // record txHashes used by delegatedTransfer event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax); event Transfer(address indexed from, address indexed to, uint amount); event AugmintTransfer(address indexed from, address indexed to, uint amount, string narrative, uint fee); event TokenIssued(uint amount); event TokenBurned(uint amount); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name function transferFrom(address from, address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function delegatedTransfer(address from, address to, uint amount, string narrative, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external; function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external; function increaseApproval(address spender, uint addedValue) external returns (bool); function decreaseApproval(address spender, uint subtractedValue) external returns (bool); function issueTo(address to, uint amount) external; // restrict it to "MonetarySupervisor" in impl.; function burn(uint amount) external; function transferAndNotify(TokenReceiver target, uint amount, uint data) external; function transferWithNarrative(address to, uint256 amount, string narrative) external; function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external; function allowance(address owner, address spender) external view returns (uint256 remaining); function balanceOf(address who) external view returns (uint); } interface TransferFeeInterface { function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee); } contract AugmintToken is AugmintTokenInterface { event FeeAccountChanged(TransferFeeInterface newFeeAccount); constructor(address permissionGranterContract, string _name, string _symbol, bytes32 _peggedSymbol, uint8 _decimals, TransferFeeInterface _feeAccount) public Restricted(permissionGranterContract) { require(_feeAccount != address(0), "feeAccount must be set"); require(bytes(_name).length > 0, "name must be set"); require(bytes(_symbol).length > 0, "symbol must be set"); name = _name; symbol = _symbol; peggedSymbol = _peggedSymbol; decimals = _decimals; feeAccount = _feeAccount; } function transfer(address to, uint256 amount) external returns (bool) { _transfer(msg.sender, to, amount, ""); return true; } /* Transfers based on an offline signed transfer instruction. */ function delegatedTransfer(address from, address to, uint amount, string narrative, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external { bytes32 txHash = keccak256(abi.encodePacked(this, from, to, amount, narrative, maxExecutorFeeInToken, nonce)); _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken); _transfer(from, to, amount, narrative); } function approve(address _spender, uint256 amount) external returns (bool) { require(_spender != 0x0, "spender must be set"); allowed[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, amount); return true; } /** ERC20 transferFrom attack protection: https://github.com/DecentLabs/dcm-poc/issues/57 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) Based on MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) external returns (bool) { return _increaseApproval(msg.sender, _spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) external 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; } function transferFrom(address from, address to, uint256 amount) external returns (bool) { _transferFrom(from, to, amount, ""); return true; } // Issue tokens. See MonetarySupervisor but as a rule of thumb issueTo is only allowed: // - on new loan (by trusted Lender contracts) // - when converting old tokens using MonetarySupervisor // - strictly to reserve by Stability Board (via MonetarySupervisor) function issueTo(address to, uint amount) external restrict("MonetarySupervisor") { balances[to] = balances[to].add(amount); totalSupply = totalSupply.add(amount); emit Transfer(0x0, to, amount); emit AugmintTransfer(0x0, to, amount, "", 0); } // Burn tokens. Anyone can burn from its own account. YOLO. // Used by to burn from Augmint reserve or by Lender contract after loan repayment function burn(uint amount) external { require(balances[msg.sender] >= amount, "balance must be >= amount"); balances[msg.sender] = balances[msg.sender].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(msg.sender, 0x0, amount); emit AugmintTransfer(msg.sender, 0x0, amount, "", 0); } /* to upgrade feeAccount (eg. for fee calculation changes) */ function setFeeAccount(TransferFeeInterface newFeeAccount) external restrict("StabilityBoard") { feeAccount = newFeeAccount; emit FeeAccountChanged(newFeeAccount); } /* transferAndNotify can be used by contracts which require tokens to have only 1 tx (instead of approve + call) Eg. repay loan, lock funds, token sell order on exchange Reverts on failue: - transfer fails - if transferNotification fails (callee must revert on failure) - if targetContract is an account or targetContract doesn't have neither transferNotification or fallback fx TODO: make data param generic bytes (see receiver code attempt in Locker.transferNotification) */ function transferAndNotify(TokenReceiver target, uint amount, uint data) external { _transfer(msg.sender, target, amount, ""); target.transferNotification(msg.sender, amount, data); } /* transferAndNotify based on an instruction signed offline */ function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external { bytes32 txHash = keccak256(abi.encodePacked(this, from, target, amount, data, maxExecutorFeeInToken, nonce)); _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken); _transfer(from, target, amount, ""); target.transferNotification(from, amount, data); } function transferWithNarrative(address to, uint256 amount, string narrative) external { _transfer(msg.sender, to, amount, narrative); } function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external { _transferFrom(from, to, amount, narrative); } function balanceOf(address _owner) external view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) external view returns (uint256 remaining) { return allowed[_owner][_spender]; } function _checkHashAndTransferExecutorFee(bytes32 txHash, bytes signature, address signer, uint maxExecutorFeeInToken, uint requestedExecutorFeeInToken) private { require(requestedExecutorFeeInToken <= maxExecutorFeeInToken, "requestedExecutorFee must be <= maxExecutorFee"); require(!delegatedTxHashesUsed[txHash], "txHash already used"); delegatedTxHashesUsed[txHash] = true; address recovered = ECRecovery.recover(ECRecovery.toEthSignedMessageHash(txHash), signature); require(recovered == signer, "invalid signature"); _transfer(signer, msg.sender, requestedExecutorFeeInToken, "Delegated transfer fee", 0); } function _increaseApproval(address _approver, address _spender, uint _addedValue) private returns (bool) { allowed[_approver][_spender] = allowed[_approver][_spender].add(_addedValue); emit Approval(_approver, _spender, allowed[_approver][_spender]); } function _transferFrom(address from, address to, uint256 amount, string narrative) private { require(balances[from] >= amount, "balance must >= amount"); require(allowed[from][msg.sender] >= amount, "allowance must be >= amount"); // don't allow 0 transferFrom if no approval: require(allowed[from][msg.sender] > 0, "allowance must be >= 0 even with 0 amount"); /* NB: fee is deducted from owner. It can result that transferFrom of amount x to fail when x + fee is not availale on owner balance */ _transfer(from, to, amount, narrative); allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount); } function _transfer(address from, address to, uint transferAmount, string narrative) private { uint fee = feeAccount.calculateTransferFee(from, to, transferAmount); _transfer(from, to, transferAmount, narrative, fee); } function _transfer(address from, address to, uint transferAmount, string narrative, uint fee) private { require(to != 0x0, "to must be set"); uint amountWithFee = transferAmount.add(fee); // to emit proper reason instead of failing on from.sub() require(balances[from] >= amountWithFee, "balance must be >= amount + transfer fee"); if (fee > 0) { balances[feeAccount] = balances[feeAccount].add(fee); emit Transfer(from, feeAccount, fee); } balances[from] = balances[from].sub(amountWithFee); balances[to] = balances[to].add(transferAmount); emit Transfer(from, to, transferAmount); emit AugmintTransfer(from, to, transferAmount, narrative, fee); } } contract SystemAccount is Restricted { event WithdrawFromSystemAccount(address tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative); constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks /* TODO: this is only for first pilots to avoid funds stuck in contract due to bugs. remove this function for higher volume pilots */ function withdraw(AugmintToken tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative) external restrict("StabilityBoard") { tokenAddress.transferWithNarrative(to, tokenAmount, narrative); if (weiAmount > 0) { to.transfer(weiAmount); } emit WithdrawFromSystemAccount(tokenAddress, to, tokenAmount, weiAmount, narrative); } } /* Contract to hold Augmint reserves (ETH & Token) - ETH as regular ETH balance of the contract - ERC20 token reserve (stored as regular Token balance under the contract address) NB: reserves are held under the contract address, therefore any transaction on the reserve is limited to the tx-s defined here (i.e. transfer is not allowed even by the contract owner or StabilityBoard or MonetarySupervisor) */ contract AugmintReserves is SystemAccount { function () public payable { // solhint-disable-line no-empty-blocks // to accept ETH sent into reserve (from defaulted loan's collateral ) } constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function burn(AugmintTokenInterface augmintToken, uint amount) external restrict("MonetarySupervisor") { augmintToken.burn(amount); } } /* Contract to hold earned interest from loans repaid premiums for locks are being accrued (i.e. transferred) to Locker */ contract InterestEarnedAccount is SystemAccount { constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function transferInterest(AugmintTokenInterface augmintToken, address locker, uint interestAmount) external restrict("MonetarySupervisor") { augmintToken.transfer(locker, interestAmount); } } /* MonetarySupervisor - maintains system wide KPIs (eg totalLockAmount, totalLoanAmount) - holds system wide parameters/limits - enforces system wide limits - burns and issues to AugmintReserves - Send funds from reserve to exchange when intervening (not implemented yet) - Converts older versions of AugmintTokens in 1:1 to new */ contract MonetarySupervisor is Restricted, TokenReceiver { // solhint-disable-line no-empty-blocks using SafeMath for uint256; uint public constant PERCENT_100 = 1000000; AugmintTokenInterface public augmintToken; InterestEarnedAccount public interestEarnedAccount; AugmintReserves public augmintReserves; uint public issuedByStabilityBoard; // token issued by Stability Board uint public totalLoanAmount; // total amount of all loans without interest, in token uint public totalLockedAmount; // total amount of all locks without premium, in token /********** Parameters to ensure totalLoanAmount or totalLockedAmount difference is within limits and system also works when total loan or lock amounts are low. for test calculations: https://docs.google.com/spreadsheets/d/1MeWYPYZRIm1n9lzpvbq8kLfQg1hhvk5oJY6NrR401S0 **********/ struct LtdParams { uint lockDifferenceLimit; /* only allow a new lock if Loan To Deposit ratio would stay above (1 - lockDifferenceLimit) with new lock. Stored as parts per million */ uint loanDifferenceLimit; /* only allow a new loan if Loan To Deposit ratio would stay above (1 + loanDifferenceLimit) with new loan. Stored as parts per million */ /* allowedDifferenceAmount param is to ensure the system is not "freezing" when totalLoanAmount or totalLockAmount is low. It allows a new loan or lock (up to an amount to reach this difference) even if LTD will go below / above lockDifferenceLimit / loanDifferenceLimit with the new lock/loan */ uint allowedDifferenceAmount; } LtdParams public ltdParams; /* Previously deployed AugmintTokens which are accepted for conversion (see transferNotification() ) NB: it's not iterable so old version addresses needs to be added for UI manually after each deploy */ mapping(address => bool) public acceptedLegacyAugmintTokens; event LtdParamsChanged(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount); event AcceptedLegacyAugmintTokenChanged(address augmintTokenAddress, bool newAcceptedState); event LegacyTokenConverted(address oldTokenAddress, address account, uint amount); event KPIsAdjusted(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment); event SystemContractsChanged(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves); constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, AugmintReserves _augmintReserves, InterestEarnedAccount _interestEarnedAccount, uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; augmintReserves = _augmintReserves; interestEarnedAccount = _interestEarnedAccount; ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); } function issueToReserve(uint amount) external restrict("StabilityBoard") { issuedByStabilityBoard = issuedByStabilityBoard.add(amount); augmintToken.issueTo(augmintReserves, amount); } function burnFromReserve(uint amount) external restrict("StabilityBoard") { issuedByStabilityBoard = issuedByStabilityBoard.sub(amount); augmintReserves.burn(augmintToken, amount); } /* Locker requesting interest when locking funds. Enforcing LTD to stay within range allowed by LTD params NB: it does not know about min loan amount, it's the loan contract's responsibility to enforce it */ function requestInterest(uint amountToLock, uint interestAmount) external { // only whitelisted Locker require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission"); require(amountToLock <= getMaxLockAmountAllowedByLtd(), "amountToLock must be <= maxLockAmountAllowedByLtd"); totalLockedAmount = totalLockedAmount.add(amountToLock); // next line would revert but require to emit reason: require(augmintToken.balanceOf(address(interestEarnedAccount)) >= interestAmount, "interestEarnedAccount balance must be >= interestAmount"); interestEarnedAccount.transferInterest(augmintToken, msg.sender, interestAmount); // transfer interest to Locker } // Locker notifying when releasing funds to update KPIs function releaseFundsNotification(uint lockedAmount) external { // only whitelisted Locker require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission"); totalLockedAmount = totalLockedAmount.sub(lockedAmount); } /* Issue loan if LTD stays within range allowed by LTD params NB: it does not know about min loan amount, it's the loan contract's responsibility to enforce it */ function issueLoan(address borrower, uint loanAmount) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); require(loanAmount <= getMaxLoanAmountAllowedByLtd(), "loanAmount must be <= maxLoanAmountAllowedByLtd"); totalLoanAmount = totalLoanAmount.add(loanAmount); augmintToken.issueTo(borrower, loanAmount); } function loanRepaymentNotification(uint loanAmount) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); totalLoanAmount = totalLoanAmount.sub(loanAmount); } // NB: this is called by Lender contract with the sum of all loans collected in batch function loanCollectionNotification(uint totalLoanAmountCollected) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); totalLoanAmount = totalLoanAmount.sub(totalLoanAmountCollected); } function setAcceptedLegacyAugmintToken(address legacyAugmintTokenAddress, bool newAcceptedState) external restrict("StabilityBoard") { acceptedLegacyAugmintTokens[legacyAugmintTokenAddress] = newAcceptedState; emit AcceptedLegacyAugmintTokenChanged(legacyAugmintTokenAddress, newAcceptedState); } function setLtdParams(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount) external restrict("StabilityBoard") { ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); emit LtdParamsChanged(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); } /* function to migrate old totalLoanAmount and totalLockedAmount from old monetarySupervisor contract when it's upgraded. Set new monetarySupervisor contract in all locker and loanManager contracts before executing this */ function adjustKPIs(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment) external restrict("StabilityBoard") { totalLoanAmount = totalLoanAmount.add(totalLoanAmountAdjustment); totalLockedAmount = totalLockedAmount.add(totalLockedAmountAdjustment); emit KPIsAdjusted(totalLoanAmountAdjustment, totalLockedAmountAdjustment); } /* to allow upgrades of InterestEarnedAccount and AugmintReserves contracts. */ function setSystemContracts(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves) external restrict("StabilityBoard") { interestEarnedAccount = newInterestEarnedAccount; augmintReserves = newAugmintReserves; emit SystemContractsChanged(newInterestEarnedAccount, newAugmintReserves); } /* User can request to convert their tokens from older AugmintToken versions in 1:1 transferNotification is called from AugmintToken's transferAndNotify Flow for converting old tokens: 1) user calls old token contract's transferAndNotify with the amount to convert, addressing the new MonetarySupervisor Contract 2) transferAndNotify transfers user's old tokens to the current MonetarySupervisor contract's address 3) transferAndNotify calls MonetarySupervisor.transferNotification 4) MonetarySupervisor checks if old AugmintToken is permitted 5) MonetarySupervisor issues new tokens to user's account in current AugmintToken 6) MonetarySupervisor burns old tokens from own balance */ function transferNotification(address from, uint amount, uint /* data, not used */ ) external { AugmintTokenInterface legacyToken = AugmintTokenInterface(msg.sender); require(acceptedLegacyAugmintTokens[legacyToken], "msg.sender must be allowed in acceptedLegacyAugmintTokens"); legacyToken.burn(amount); augmintToken.issueTo(from, amount); emit LegacyTokenConverted(msg.sender, from, amount); } function getLoanToDepositRatio() external view returns (uint loanToDepositRatio) { loanToDepositRatio = totalLockedAmount == 0 ? 0 : totalLockedAmount.mul(PERCENT_100).div(totalLoanAmount); } /* Helper function for UI. Returns max lock amount based on minLockAmount, interestPt, using LTD params & interestEarnedAccount balance */ function getMaxLockAmount(uint minLockAmount, uint interestPt) external view returns (uint maxLock) { uint allowedByEarning = augmintToken.balanceOf(address(interestEarnedAccount)).mul(PERCENT_100).div(interestPt); uint allowedByLtd = getMaxLockAmountAllowedByLtd(); maxLock = allowedByEarning < allowedByLtd ? allowedByEarning : allowedByLtd; maxLock = maxLock < minLockAmount ? 0 : maxLock; } /* Helper function for UI. Returns max loan amount based on minLoanAmont using LTD params */ function getMaxLoanAmount(uint minLoanAmount) external view returns (uint maxLoan) { uint allowedByLtd = getMaxLoanAmountAllowedByLtd(); maxLoan = allowedByLtd < minLoanAmount ? 0 : allowedByLtd; } /* returns maximum lockable token amount allowed by LTD params. */ function getMaxLockAmountAllowedByLtd() public view returns(uint maxLockByLtd) { uint allowedByLtdDifferencePt = totalLoanAmount.mul(PERCENT_100).div(PERCENT_100 .sub(ltdParams.lockDifferenceLimit)); allowedByLtdDifferencePt = totalLockedAmount >= allowedByLtdDifferencePt ? 0 : allowedByLtdDifferencePt.sub(totalLockedAmount); uint allowedByLtdDifferenceAmount = totalLockedAmount >= totalLoanAmount.add(ltdParams.allowedDifferenceAmount) ? 0 : totalLoanAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLockedAmount); maxLockByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ? allowedByLtdDifferencePt : allowedByLtdDifferenceAmount; } /* returns maximum borrowable token amount allowed by LTD params */ function getMaxLoanAmountAllowedByLtd() public view returns(uint maxLoanByLtd) { uint allowedByLtdDifferencePt = totalLockedAmount.mul(ltdParams.loanDifferenceLimit.add(PERCENT_100)) .div(PERCENT_100); allowedByLtdDifferencePt = totalLoanAmount >= allowedByLtdDifferencePt ? 0 : allowedByLtdDifferencePt.sub(totalLoanAmount); uint allowedByLtdDifferenceAmount = totalLoanAmount >= totalLockedAmount.add(ltdParams.allowedDifferenceAmount) ? 0 : totalLockedAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLoanAmount); maxLoanByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ? allowedByLtdDifferencePt : allowedByLtdDifferenceAmount; } } contract Locker is Restricted, TokenReceiver { using SafeMath for uint256; uint public constant CHUNK_SIZE = 100; event NewLockProduct(uint32 indexed lockProductId, uint32 perTermInterest, uint32 durationInSecs, uint32 minimumLockAmount, bool isActive); event LockProductActiveChange(uint32 indexed lockProductId, bool newActiveState); // NB: amountLocked includes the original amount, plus interest event NewLock(address indexed lockOwner, uint lockId, uint amountLocked, uint interestEarned, uint40 lockedUntil, uint32 perTermInterest, uint32 durationInSecs); event LockReleased(address indexed lockOwner, uint lockId); event MonetarySupervisorChanged(MonetarySupervisor newMonetarySupervisor); struct LockProduct { // perTermInterest is in millionths (i.e. 1,000,000 = 100%): uint32 perTermInterest; uint32 durationInSecs; uint32 minimumLockAmount; bool isActive; } /* NB: we don't need to store lock parameters because lockProducts can't be altered (only disabled/enabled) */ struct Lock { uint amountLocked; address owner; uint32 productId; uint40 lockedUntil; bool isActive; } AugmintTokenInterface public augmintToken; MonetarySupervisor public monetarySupervisor; LockProduct[] public lockProducts; Lock[] public locks; // lock ids for an account mapping(address => uint[]) public accountLocks; constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, MonetarySupervisor _monetarySupervisor) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; monetarySupervisor = _monetarySupervisor; } function addLockProduct(uint32 perTermInterest, uint32 durationInSecs, uint32 minimumLockAmount, bool isActive) external restrict("StabilityBoard") { uint _newLockProductId = lockProducts.push( LockProduct(perTermInterest, durationInSecs, minimumLockAmount, isActive)) - 1; uint32 newLockProductId = uint32(_newLockProductId); require(newLockProductId == _newLockProductId, "lockProduct overflow"); emit NewLockProduct(newLockProductId, perTermInterest, durationInSecs, minimumLockAmount, isActive); } function setLockProductActiveState(uint32 lockProductId, bool isActive) external restrict("StabilityBoard") { // next line would revert but require to emit reason: require(lockProductId < lockProducts.length, "invalid lockProductId"); lockProducts[lockProductId].isActive = isActive; emit LockProductActiveChange(lockProductId, isActive); } /* lock funds, called from AugmintToken's transferAndNotify Flow for locking tokens: 1) user calls token contract's transferAndNotify lockProductId passed in data arg 2) transferAndNotify transfers tokens to the Lock contract 3) transferAndNotify calls Lock.transferNotification with lockProductId */ function transferNotification(address from, uint256 amountToLock, uint _lockProductId) external { require(msg.sender == address(augmintToken), "msg.sender must be augmintToken"); // next line would revert but require to emit reason: require(lockProductId < lockProducts.length, "invalid lockProductId"); uint32 lockProductId = uint32(_lockProductId); require(lockProductId == _lockProductId, "lockProductId overflow"); /* TODO: make data arg generic bytes uint productId; assembly { // solhint-disable-line no-inline-assembly productId := mload(data) } */ _createLock(lockProductId, from, amountToLock); } function releaseFunds(uint lockId) external { // next line would revert but require to emit reason: require(lockId < locks.length, "invalid lockId"); Lock storage lock = locks[lockId]; LockProduct storage lockProduct = lockProducts[lock.productId]; require(lock.isActive, "lock must be in active state"); require(now >= lock.lockedUntil, "current time must be later than lockedUntil"); lock.isActive = false; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); monetarySupervisor.releaseFundsNotification(lock.amountLocked); // to maintain totalLockAmount augmintToken.transferWithNarrative(lock.owner, lock.amountLocked.add(interestEarned), "Funds released from lock"); emit LockReleased(lock.owner, lockId); } function setMonetarySupervisor(MonetarySupervisor newMonetarySupervisor) external restrict("StabilityBoard") { monetarySupervisor = newMonetarySupervisor; emit MonetarySupervisorChanged(newMonetarySupervisor); } function getLockProductCount() external view returns (uint) { return lockProducts.length; } // returns 20 lock products starting from some offset // lock products are encoded as [ perTermInterest, durationInSecs, minimumLockAmount, maxLockAmount, isActive ] function getLockProducts(uint offset) external view returns (uint[5][CHUNK_SIZE] response) { for (uint8 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= lockProducts.length) { break; } LockProduct storage lockProduct = lockProducts[offset + i]; response[i] = [ lockProduct.perTermInterest, lockProduct.durationInSecs, lockProduct.minimumLockAmount, monetarySupervisor.getMaxLockAmount(lockProduct.minimumLockAmount, lockProduct.perTermInterest), lockProduct.isActive ? 1 : 0 ]; } } function getLockCount() external view returns (uint) { return locks.length; } function getLockCountForAddress(address lockOwner) external view returns (uint) { return accountLocks[lockOwner].length; } // returns CHUNK_SIZE locks starting from some offset // lock products are encoded as // [lockId, owner, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ] // NB: perTermInterest is in millionths (i.e. 1,000,000 = 100%): function getLocks(uint offset) external view returns (uint[8][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= locks.length) { break; } Lock storage lock = locks[offset + i]; LockProduct storage lockProduct = lockProducts[lock.productId]; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); response[i] = [uint(offset + i), uint(lock.owner), lock.amountLocked, interestEarned, lock.lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0]; } } // returns CHUNK_SIZE locks of a given account, starting from some offset // lock products are encoded as // [lockId, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ] function getLocksForAddress(address lockOwner, uint offset) external view returns (uint[7][CHUNK_SIZE] response) { uint[] storage locksForAddress = accountLocks[lockOwner]; for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= locksForAddress.length) { break; } Lock storage lock = locks[locksForAddress[offset + i]]; LockProduct storage lockProduct = lockProducts[lock.productId]; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); response[i] = [ locksForAddress[offset + i], lock.amountLocked, interestEarned, lock.lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0 ]; } } function calculateInterest(uint32 perTermInterest, uint amountToLock) public pure returns (uint interestEarned) { interestEarned = amountToLock.mul(perTermInterest).div(1000000); } // Internal function. assumes amountToLock is already transferred to this Lock contract function _createLock(uint32 lockProductId, address lockOwner, uint amountToLock) internal returns(uint lockId) { LockProduct storage lockProduct = lockProducts[lockProductId]; require(lockProduct.isActive, "lockProduct must be in active state"); require(amountToLock >= lockProduct.minimumLockAmount, "amountToLock must be >= minimumLockAmount"); uint interestEarned = calculateInterest(lockProduct.perTermInterest, amountToLock); uint expiration = now.add(lockProduct.durationInSecs); uint40 lockedUntil = uint40(expiration); require(lockedUntil == expiration, "lockedUntil overflow"); lockId = locks.push(Lock(amountToLock, lockOwner, lockProductId, lockedUntil, true)) - 1; accountLocks[lockOwner].push(lockId); monetarySupervisor.requestInterest(amountToLock, interestEarned); // update KPIs & transfer interest here emit NewLock(lockOwner, lockId, amountToLock, interestEarned, lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs); } }
NB: we don't need to store lock parameters because lockProducts can't be altered (only disabled/enabled) */
struct Lock { uint amountLocked; address owner; uint32 productId; uint40 lockedUntil; bool isActive; } AugmintTokenInterface public augmintToken; MonetarySupervisor public monetarySupervisor; LockProduct[] public lockProducts; Lock[] public locks; constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, MonetarySupervisor _monetarySupervisor)
978,550
[ 1, 20626, 30, 732, 2727, 1404, 1608, 358, 1707, 2176, 1472, 2724, 2176, 13344, 848, 1404, 506, 22349, 261, 3700, 5673, 19, 5745, 13, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 3488, 288, 203, 3639, 2254, 3844, 8966, 31, 203, 3639, 1758, 3410, 31, 203, 3639, 2254, 1578, 23820, 31, 203, 3639, 2254, 7132, 8586, 9716, 31, 203, 3639, 1426, 15083, 31, 203, 565, 289, 203, 203, 565, 432, 637, 81, 474, 1345, 1358, 1071, 31350, 81, 474, 1345, 31, 203, 565, 26196, 8051, 10227, 1071, 31198, 8051, 10227, 31, 203, 203, 565, 3488, 4133, 8526, 1071, 2176, 13344, 31, 203, 203, 565, 3488, 8526, 1071, 13046, 31, 203, 203, 203, 565, 3885, 12, 2867, 4132, 43, 2450, 387, 8924, 16, 432, 637, 81, 474, 1345, 1358, 389, 6480, 81, 474, 1345, 16, 203, 10792, 26196, 8051, 10227, 389, 2586, 14911, 8051, 10227, 13, 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 ]
pragma solidity ^0.5; /* NOTE: @kleros/kleros-interraction is not compatible with this solc version */ /* NOTE: I put all the arbitration files in the same file because the dependancy between the different contracts is a real "headache" */ /* If someone takes up the challenge, a PR is welcome */ /** * @title CappedMath * @dev Math operations with caps for under and overflow. * NOTE: see https://raw.githubusercontent.com/kleros/kleros-interaction/master/contracts/libraries/CappedMath.sol */ library CappedMath { uint constant private UINT_MAX = 2**256 - 1; /** * @dev Adds two unsigned integers, returns 2^256 - 1 on overflow. */ function addCap(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; return c >= _a ? c : UINT_MAX; } /** * @dev Subtracts two integers, returns 0 on underflow. */ function subCap(uint _a, uint _b) internal pure returns (uint) { if (_b > _a) return 0; else return _a - _b; } /** * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow. */ function mulCap(uint _a, uint _b) internal pure returns (uint) { // 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; uint c = _a * _b; return c / _a == _b ? c : UINT_MAX; } } /** @title IArbitrable * Arbitrable interface. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ interface IArbitrable { /** @dev To be emmited when meta-evidence is submitted. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidence A link to the meta-evidence JSON. */ event MetaEvidence(uint indexed _metaEvidenceID, string _evidence); /** @dev To be emmited when a dispute is created to link the correct meta-evidence to the disputeID * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute. */ event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID); /** @dev To be raised when evidence are submitted. Should point to the ressource (evidences are not to be stored on chain due to gas considerations). * @param _arbitrator The arbitrator of the contract. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. * @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party. * @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json. */ event Evidence(Arbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence); /** @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) external; } /** @title Arbitrable * Arbitrable abstract contract. * When developing arbitrable contracts, we need to: * -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. * -Allow dispute creation. For this a function must: * -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); * -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); */ contract Arbitrable is IArbitrable { Arbitrator public arbitrator; bytes public arbitratorExtraData; // Extra data to require particular dispute and appeal behaviour. /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. */ constructor(Arbitrator _arbitrator, bytes memory _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { emit Ruling(Arbitrator(msg.sender), _disputeID, _ruling); executeRuling(_disputeID, _ruling); } /** @dev Execute a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal; } /** @title Arbitrator * Arbitrator abstract contract. * When developing arbitrator contracts we need to: * -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, use nbDisputes). * -Define the functions for cost display (arbitrationCost and appealCost). * -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling). */ contract Arbitrator { enum DisputeStatus {Waiting, Appealable, Solved} modifier requireArbitrationFee(bytes memory _extraData) { require(msg.value >= arbitrationCost(_extraData), "Not enough ETH to cover arbitration costs."); _; } modifier requireAppealFee(uint _disputeID, bytes memory _extraData) { require(msg.value >= appealCost(_disputeID, _extraData), "Not enough ETH to cover appeal costs."); _; } /** @dev To be raised when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when a dispute can be appealed. * @param _disputeID ID of the dispute. */ event AppealPossible(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev To be raised when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, Arbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes memory _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function arbitrationCost(bytes memory _extraData) public view returns(uint fee); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes memory _extraData) public requireAppealFee(_disputeID,_extraData) payable { emit AppealDecision(_disputeID, Arbitrable(msg.sender)); } /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint fee); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) {} /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) public view returns(uint ruling); } /** @title Centralized Arbitrator * @dev This is a centralized arbitrator deciding alone on the result of disputes. No appeals are possible. */ contract CentralizedArbitrator is Arbitrator { address public owner = msg.sender; uint arbitrationPrice; // Not public because arbitrationCost already acts as an accessor. uint constant NOT_PAYABLE_VALUE = (2**256-2)/2; // High value to be sure that the appeal is too expensive. struct DisputeStruct { Arbitrable arbitrated; uint choices; uint fee; uint ruling; DisputeStatus status; } modifier onlyOwner {require(msg.sender==owner, "Can only be called by the owner."); _;} DisputeStruct[] public disputes; /** @dev Constructor. Set the initial arbitration price. * @param _arbitrationPrice Amount to be paid for arbitration. */ constructor(uint _arbitrationPrice) public { arbitrationPrice = _arbitrationPrice; } /** @dev Set the arbitration price. Only callable by the owner. * @param _arbitrationPrice Amount to be paid for arbitration. */ function setArbitrationPrice(uint _arbitrationPrice) public onlyOwner { arbitrationPrice = _arbitrationPrice; } /** @dev Cost of arbitration. Accessor to arbitrationPrice. * @param _extraData Not used by this contract. * @return fee Amount to be paid. */ function arbitrationCost(bytes memory _extraData) public view returns(uint fee) { return arbitrationPrice; } /** @dev Cost of appeal. Since it is not possible, it's a high value which can never be paid. * @param _disputeID ID of the dispute to be appealed. Not used by this contract. * @param _extraData Not used by this contract. * @return fee Amount to be paid. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint fee) { return NOT_PAYABLE_VALUE; } /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(). * @param _choices Amount of choices the arbitrator can make in this dispute. When ruling ruling<=choices. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes memory _extraData) public payable returns(uint disputeID) { super.createDispute(_choices, _extraData); disputeID = disputes.push(DisputeStruct({ arbitrated: Arbitrable(msg.sender), choices: _choices, fee: msg.value, ruling: 0, status: DisputeStatus.Waiting })) - 1; // Create the dispute and return its number. emit DisputeCreation(disputeID, Arbitrable(msg.sender)); } /** @dev Give a ruling. UNTRUSTED. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision". */ function _giveRuling(uint _disputeID, uint _ruling) internal { DisputeStruct storage dispute = disputes[_disputeID]; require(_ruling <= dispute.choices, "Invalid ruling."); require(dispute.status != DisputeStatus.Solved, "The dispute must not be solved already."); dispute.ruling = _ruling; dispute.status = DisputeStatus.Solved; msg.sender.send(dispute.fee); // Avoid blocking. dispute.arbitrated.rule(_disputeID,_ruling); } /** @dev Give a ruling. UNTRUSTED. * @param _disputeID ID of the dispute to rule. * @param _ruling Ruling given by the arbitrator. Note that 0 means "Not able/wanting to make a decision". */ function giveRuling(uint _disputeID, uint _ruling) public onlyOwner { return _giveRuling(_disputeID, _ruling); } /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { return disputes[_disputeID].status; } /** @dev Return the ruling of a dispute. * @param _disputeID ID of the dispute to rule. * @return ruling The ruling which would or has been given. */ function currentRuling(uint _disputeID) public view returns(uint ruling) { return disputes[_disputeID].ruling; } } /** * @title AppealableArbitrator * @dev A centralized arbitrator that can be appealed. */ contract AppealableArbitrator is CentralizedArbitrator, Arbitrable { /* Structs */ struct AppealDispute { uint rulingTime; Arbitrator arbitrator; uint appealDisputeID; } /* Storage */ uint public timeOut; mapping(uint => AppealDispute) public appealDisputes; mapping(uint => uint) public appealDisputeIDsToDisputeIDs; /* Constructor */ /** @dev Constructs the `AppealableArbitrator` contract. * @param _arbitrationPrice The amount to be paid for arbitration. * @param _arbitrator The back up arbitrator. * @param _arbitratorExtraData Not used by this contract. * @param _timeOut The time out for the appeal period. */ constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut ) public CentralizedArbitrator(_arbitrationPrice) Arbitrable(_arbitrator, _arbitratorExtraData) { timeOut = _timeOut; } /* External */ /** @dev Changes the back up arbitrator. * @param _arbitrator The new back up arbitrator. */ function changeArbitrator(Arbitrator _arbitrator) external onlyOwner { arbitrator = _arbitrator; } /** @dev Changes the time out. * @param _timeOut The new time out. */ function changeTimeOut(uint _timeOut) external onlyOwner { timeOut = _timeOut; } /* External Views */ /** @dev Gets the specified dispute's latest appeal ID. * @param _disputeID The ID of the dispute. */ function getAppealDisputeID(uint _disputeID) external view returns(uint disputeID) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) disputeID = AppealableArbitrator(address(appealDisputes[_disputeID].arbitrator)).getAppealDisputeID(appealDisputes[_disputeID].appealDisputeID); else disputeID = _disputeID; } /* Public */ /** @dev Appeals a ruling. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. */ function appeal(uint _disputeID, bytes memory _extraData) public payable requireAppealFee(_disputeID, _extraData) { super.appeal(_disputeID, _extraData); if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) appealDisputes[_disputeID].arbitrator.appeal.value(msg.value)(appealDisputes[_disputeID].appealDisputeID, _extraData); else { appealDisputes[_disputeID].arbitrator = arbitrator; appealDisputes[_disputeID].appealDisputeID = arbitrator.createDispute.value(msg.value)(disputes[_disputeID].choices, _extraData); appealDisputeIDsToDisputeIDs[appealDisputes[_disputeID].appealDisputeID] = _disputeID; } } /** @dev Gives a ruling. * @param _disputeID The ID of the dispute. * @param _ruling The ruling. */ function giveRuling(uint _disputeID, uint _ruling) public { require(disputes[_disputeID].status != DisputeStatus.Solved, "The specified dispute is already resolved."); if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) { require(Arbitrator(msg.sender) == appealDisputes[_disputeID].arbitrator, "Appealed disputes must be ruled by their back up arbitrator."); super._giveRuling(_disputeID, _ruling); } else { require(msg.sender == owner, "Not appealed disputes must be ruled by the owner."); if (disputes[_disputeID].status == DisputeStatus.Appealable) { if (now - appealDisputes[_disputeID].rulingTime > timeOut) super._giveRuling(_disputeID, disputes[_disputeID].ruling); else revert("Time out time has not passed yet."); } else { disputes[_disputeID].ruling = _ruling; disputes[_disputeID].status = DisputeStatus.Appealable; appealDisputes[_disputeID].rulingTime = now; emit AppealPossible(_disputeID, disputes[_disputeID].arbitrated); } } } /* Public Views */ /** @dev Gets the cost of appeal for the specified dispute. * @param _disputeID The ID of the dispute. * @param _extraData Additional info about the appeal. * @return The cost of the appeal. */ function appealCost(uint _disputeID, bytes memory _extraData) public view returns(uint cost) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) cost = appealDisputes[_disputeID].arbitrator.appealCost(appealDisputes[_disputeID].appealDisputeID, _extraData); else if (disputes[_disputeID].status == DisputeStatus.Appealable) cost = arbitrator.arbitrationCost(_extraData); else cost = NOT_PAYABLE_VALUE; } /** @dev Gets the status of the specified dispute. * @param _disputeID The ID of the dispute. * @return The status. */ function disputeStatus(uint _disputeID) public view returns(DisputeStatus status) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) status = appealDisputes[_disputeID].arbitrator.disputeStatus(appealDisputes[_disputeID].appealDisputeID); else status = disputes[_disputeID].status; } /** @dev Return the ruling of a dispute. * @param _disputeID ID of the dispute to rule. * @return ruling The ruling which would or has been given. */ function currentRuling(uint _disputeID) public view returns(uint ruling) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) // Appealed. ruling = appealDisputes[_disputeID].arbitrator.currentRuling(appealDisputes[_disputeID].appealDisputeID); // Retrieve ruling from the arbitrator whom the dispute is appealed to. else ruling = disputes[_disputeID].ruling; // Not appealed, basic case. } /* Internal */ /** @dev Executes the ruling of the specified dispute. * @param _disputeID The ID of the dispute. * @param _ruling The ruling. */ function executeRuling(uint _disputeID, uint _ruling) internal { require( appealDisputes[appealDisputeIDsToDisputeIDs[_disputeID]].arbitrator != Arbitrator(address(0)), "The dispute must have been appealed." ); giveRuling(appealDisputeIDsToDisputeIDs[_disputeID], _ruling); } } /** * @title EnhancedAppealableArbitrator * @author Enrique Piqueras - <[email protected]> * @dev Implementation of `AppealableArbitrator` that supports `appealPeriod`. */ contract EnhancedAppealableArbitrator is AppealableArbitrator { /* Constructor */ /** @dev Constructs the `EnhancedAppealableArbitrator` contract. * @param _arbitrationPrice The amount to be paid for arbitration. * @param _arbitrator The back up arbitrator. * @param _arbitratorExtraData Not used by this contract. * @param _timeOut The time out for the appeal period. */ constructor( uint _arbitrationPrice, Arbitrator _arbitrator, bytes memory _arbitratorExtraData, uint _timeOut ) public AppealableArbitrator(_arbitrationPrice, _arbitrator, _arbitratorExtraData, _timeOut) {} /* Public Views */ /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) public view returns(uint start, uint end) { if (appealDisputes[_disputeID].arbitrator != Arbitrator(address(0))) (start, end) = appealDisputes[_disputeID].arbitrator.appealPeriod(appealDisputes[_disputeID].appealDisputeID); else { start = appealDisputes[_disputeID].rulingTime; require(start != 0, "The specified dispute is not appealable."); end = start + timeOut; } } } /** * @title Permission Interface * This is a permission interface for arbitrary values. The values can be cast to the required types. */ interface PermissionInterface { /** * @dev Return true if the value is allowed. * @param _value The value we want to check. * @return allowed True if the value is allowed, false otherwise. */ function isPermitted(bytes32 _value) external view returns (bool allowed); } /** * @title ArbitrableBetList * This smart contract is a viewer moderation for the bet goal contract. * This is working progress. */ contract ArbitrableBetList is IArbitrable { using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1. /* Enums */ enum BetStatus { Absent, // The bet is not in the registry. Registered, // The bet is in the registry. RegistrationRequested, // The bet has a request to be added to the registry. ClearingRequested // The bet has a request to be removed from the registry. } enum Party { None, // Party per default when there is no challenger or requester. Also used for unconclusive ruling. Requester, // Party that made the request to change a bet status. Challenger // Party that challenges the request to change a bet status. } // ************************ // // * Request Life Cycle * // // ************************ // // Changes to the bet status are made via requests for either listing or removing a bet from the Bet Curated Registry. // To make or challenge a request, a party must pay a deposit. This value will be rewarded to the party that ultimately wins a dispute. If no one challenges the request, the value will be reimbursed to the requester. // Additionally to the challenge reward, in the case a party challenges a request, both sides must fully pay the amount of arbitration fees required to raise a dispute. The party that ultimately wins the case will be reimbursed. // Finally, arbitration fees can be crowdsourced. To incentivise insurers, an additional fee stake must be deposited. Contributors that fund the side that ultimately wins a dispute will be reimbursed and rewarded with the other side's fee stake proportionally to their contribution. // In summary, costs for placing or challenging a request are the following: // - A challenge reward given to the party that wins a potential dispute. // - Arbitration fees used to pay jurors. // - A fee stake that is distributed among insurers of the side that ultimately wins a dispute. /* Structs */ struct Bet { BetStatus status; // The status of the bet. Request[] requests; // List of status change requests made for the bet. } // Some arrays below have 3 elements to map with the Party enums for better readability: // - 0: is unused, matches `Party.None`. // - 1: for `Party.Requester`. // - 2: for `Party.Challenger`. struct Request { bool disputed; // True if a dispute was raised. uint disputeID; // ID of the dispute, if any. uint submissionTime; // Time when the request was made. Used to track when the challenge period ends. bool resolved; // True if the request was executed and/or any disputes raised were resolved. address[3] parties; // Address of requester and challenger, if any. Round[] rounds; // Tracks each round of a dispute. Party ruling; // The final ruling given, if any. Arbitrator arbitrator; // The arbitrator trusted to solve disputes for this request. bytes arbitratorExtraData; // The extra data for the trusted arbitrator of this request. } struct Round { uint[3] paidFees; // Tracks the fees paid by each side on this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => uint[3]) contributions; // Maps contributors to their contributions for each side. } /* Storage */ // Constants uint RULING_OPTIONS = 2; // The amount of non 0 choices the arbitrator can give. // Settings address public governor; // The address that can make governance changes to the parameters of the Bet Curated Registry. Arbitrator arbitrator; bytes public arbitratorExtraData; address public selfCommitmentRegistry; // The address of the selfCommitmentRegistry contract. uint public requesterBaseDeposit; // The base deposit to make a request. uint public challengerBaseDeposit; // The base deposit to challenge a request. uint public challengePeriodDuration; // The time before a request becomes executable if not challenged. uint public metaEvidenceUpdates; // The number of times the meta evidence has been updated. Used to track the latest meta evidence ID. // The required fee stake that a party must pay depends on who won the previous round and is proportional to the arbitration cost such that the fee stake for a round is stake multiplier * arbitration cost for that round. // Multipliers are in basis points. uint public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round. uint public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round. uint public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where there isn't a winner and loser (e.g. when it's the first round or the arbitrator ruled "refused to rule"/"could not rule"). uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. // Registry data. mapping(uint => Bet) public bets; // Maps the uint bet to the bet data. mapping(address => mapping(uint => uint)) public arbitratorDisputeIDToBetID; // Maps a dispute ID to the bet with the disputed request. uint[] public betList; // List of submitted bets. /* Modifiers */ modifier onlyGovernor {require(msg.sender == governor, "The caller must be the governor."); _;} /* Events */ /** * @dev Emitted when a party submits a new bet. * @param _betID The bet. * @param _requester The address of the party that made the request. */ event BetSubmitted(uint indexed _betID, address indexed _requester); /** @dev Emitted when a party makes a request to change a bet status. * @param _betID The bet index. * @param _registrationRequest Whether the request is a registration request. False means it is a clearing request. */ event RequestSubmitted(uint indexed _betID, bool _registrationRequest); /** * @dev Emitted when a party makes a request, dispute or appeals are raised, or when a request is resolved. * @param _requester Address of the party that submitted the request. * @param _challenger Address of the party that has challenged the request, if any. * @param _betID The address. * @param _status The status of the bet. * @param _disputed Whether the bet is disputed. * @param _appealed Whether the current round was appealed. */ event BetStatusChange( address indexed _requester, address indexed _challenger, uint indexed _betID, BetStatus _status, bool _disputed, bool _appealed ); /** @dev Emitted when a reimbursements and/or contribution rewards are withdrawn. * @param _betID The bet ID from which the withdrawal was made. * @param _contributor The address that sent the contribution. * @param _request The request from which the withdrawal was made. * @param _round The round from which the reward was taken. * @param _value The value of the reward. */ event RewardWithdrawal(uint indexed _betID, address indexed _contributor, uint indexed _request, uint _round, uint _value); /* Constructor */ /** * @dev Constructs the arbitrable token curated registry. * @param _arbitrator The trusted arbitrator to resolve potential disputes. * @param _arbitratorExtraData Extra data for the trusted arbitrator contract. * @param _registrationMetaEvidence The URI of the meta evidence object for registration requests. * @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests. * @param _governor The trusted governor of this contract. * @param _requesterBaseDeposit The base deposit to make a request. * @param _challengerBaseDeposit The base deposit to challenge a request. * @param _challengePeriodDuration The time in seconds, parties have to challenge a request. * @param _sharedStakeMultiplier Multiplier of the arbitration cost that each party must pay as fee stake for a round when there isn't a winner/loser in the previous round (e.g. when it's the first round or the arbitrator refused to or did not rule). In basis points. * @param _winnerStakeMultiplier Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. * @param _loserStakeMultiplier Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. */ constructor( Arbitrator _arbitrator, bytes memory _arbitratorExtraData, string memory _registrationMetaEvidence, string memory _clearingMetaEvidence, address _governor, uint _requesterBaseDeposit, uint _challengerBaseDeposit, uint _challengePeriodDuration, uint _sharedStakeMultiplier, uint _winnerStakeMultiplier, uint _loserStakeMultiplier ) public { emit MetaEvidence(0, _registrationMetaEvidence); emit MetaEvidence(1, _clearingMetaEvidence); governor = _governor; arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; requesterBaseDeposit = _requesterBaseDeposit; challengerBaseDeposit = _challengerBaseDeposit; challengePeriodDuration = _challengePeriodDuration; sharedStakeMultiplier = _sharedStakeMultiplier; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; } /* External and Public */ // ************************ // // * Requests * // // ************************ // /** @dev Submits a request to change an address status. Accepts enough ETH to fund a potential dispute considering the current required amount and reimburses the rest. TRUSTED. * @param _betID The address. * @param _sender The address of the sender. */ function requestStatusChange(uint _betID, address payable _sender) external payable { Bet storage bet = bets[_betID]; if (bet.requests.length == 0) { // Initial bet registration. require(msg.sender == selfCommitmentRegistry); betList.push(_betID); emit BetSubmitted(_betID, _sender); } // Update bet status. if (bet.status == BetStatus.Absent) bet.status = BetStatus.RegistrationRequested; else if (bet.status == BetStatus.Registered) bet.status = BetStatus.ClearingRequested; else revert("Bet already has a pending request."); // Setup request. Request storage request = bet.requests[bet.requests.length++]; request.parties[uint(Party.Requester)] = _sender; request.submissionTime = now; request.arbitrator = arbitrator; request.arbitratorExtraData = arbitratorExtraData; Round storage round = request.rounds[request.rounds.length++]; emit RequestSubmitted(_betID, bet.status == BetStatus.RegistrationRequested); // Amount required to fully the requester: requesterBaseDeposit + arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = request.arbitrator.arbitrationCost(request.arbitratorExtraData); uint totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(requesterBaseDeposit); contribute(round, Party.Requester, _sender, msg.value, totalCost); require(round.paidFees[uint(Party.Requester)] >= totalCost, "You must fully fund your side."); round.hasPaid[uint(Party.Requester)] = true; emit BetStatusChange( request.parties[uint(Party.Requester)], address(0x0), _betID, bet.status, false, false ); } /** @dev Get the total cost */ function getTotalCost() external view returns (uint totalCost) { uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(requesterBaseDeposit); } /** @dev Challenges the latest request of a bet. Accepts enough ETH to fund a potential dispute considering the current required amount. Reimburses unused ETH. TRUSTED. * @param _betID The bet ID with the request to challenge. * @param _evidence A link to an evidence using its URI. Ignored if not provided or if not enough funds were provided to create a dispute. */ function challengeRequest(uint _betID, string calldata _evidence) external payable { Bet storage bet = bets[_betID]; require( bet.status == BetStatus.RegistrationRequested || bet.status == BetStatus.ClearingRequested, "The bet must have a pending request." ); Request storage request = bet.requests[bet.requests.length - 1]; require(now - request.submissionTime <= challengePeriodDuration, "Challenges must occur during the challenge period."); require(!request.disputed, "The request should not have already been disputed."); // Take the deposit and save the challenger's bet. request.parties[uint(Party.Challenger)] = msg.sender; Round storage round = request.rounds[request.rounds.length - 1]; uint arbitrationCost = request.arbitrator.arbitrationCost(request.arbitratorExtraData); uint totalCost = arbitrationCost.addCap((arbitrationCost.mulCap(sharedStakeMultiplier)) / MULTIPLIER_DIVISOR).addCap(challengerBaseDeposit); contribute(round, Party.Challenger, msg.sender, msg.value, totalCost); require(round.paidFees[uint(Party.Challenger)] >= totalCost, "You must fully fund your side."); round.hasPaid[uint(Party.Challenger)] = true; // Raise a dispute. request.disputeID = request.arbitrator.createDispute.value(arbitrationCost)(RULING_OPTIONS, request.arbitratorExtraData); arbitratorDisputeIDToBetID[address(request.arbitrator)][request.disputeID] = _betID; request.disputed = true; request.rounds.length++; round.feeRewards = round.feeRewards.subCap(arbitrationCost); emit Dispute( request.arbitrator, request.disputeID, bet.status == BetStatus.RegistrationRequested ? 2 * metaEvidenceUpdates : 2 * metaEvidenceUpdates + 1, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))) ); emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], _betID, bet.status, true, false ); if (bytes(_evidence).length > 0) emit Evidence(request.arbitrator, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))), msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. TRUSTED. * @param _betID The bet index. * @param _side The recipient of the contribution. */ function fundAppeal(uint _betID, Party _side) external payable { // Recipient must be either the requester or challenger. require(_side == Party.Requester || _side == Party.Challenger); // solium-disable-line error-reason Bet storage bet = bets[_betID]; require( bet.status == BetStatus.RegistrationRequested || bet.status == BetStatus.ClearingRequested, "The bet must have a pending request." ); Request storage request = bet.requests[bet.requests.length - 1]; require(request.disputed, "A dispute must have been raised to fund an appeal."); (uint appealPeriodStart, uint appealPeriodEnd) = request.arbitrator.appealPeriod(request.disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Contributions must be made within the appeal period." ); // Amount required to fully fund each side: arbitration cost + (arbitration cost * multiplier) Round storage round = request.rounds[request.rounds.length - 1]; Party winner = Party(request.arbitrator.currentRuling(request.disputeID)); Party loser; if (winner == Party.Requester) loser = Party.Challenger; else if (winner == Party.Challenger) loser = Party.Requester; require(!(_side==loser) || (now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2), "The loser must contribute during the first half of the appeal period."); uint multiplier; if (_side == winner) multiplier = winnerStakeMultiplier; else if (_side == loser) multiplier = loserStakeMultiplier; else multiplier = sharedStakeMultiplier; uint appealCost = request.arbitrator.appealCost(request.disputeID, request.arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); contribute(round, _side, msg.sender, msg.value, totalCost); if (round.paidFees[uint(_side)] >= totalCost) round.hasPaid[uint(_side)] = true; // Raise appeal if both sides are fully funded. if (round.hasPaid[uint(Party.Challenger)] && round.hasPaid[uint(Party.Requester)]) { request.arbitrator.appeal.value(appealCost)(request.disputeID, request.arbitratorExtraData); request.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], _betID, bet.status, true, true ); } } /** @dev Reimburses contributions if no disputes were raised. If a dispute was raised, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * @param _beneficiary The address that made contributions to a request. * @param _betID The bet index submission with the request from which to withdraw. * @param _request The request from which to withdraw. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards(address payable _beneficiary, uint _betID, uint _request, uint _round) public { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; Round storage round = request.rounds[_round]; // The request must be executed and there can be no disputes pending resolution. require(request.resolved); // solium-disable-line error-reason uint reward; if (!round.hasPaid[uint(Party.Requester)] || !round.hasPaid[uint(Party.Challenger)]) { // Reimburse if not enough fees were raised to appeal the ruling. reward = round.contributions[_beneficiary][uint(Party.Requester)] + round.contributions[_beneficiary][uint(Party.Challenger)]; round.contributions[_beneficiary][uint(Party.Requester)] = 0; round.contributions[_beneficiary][uint(Party.Challenger)] = 0; } else if (request.ruling == Party.None) { // No disputes were raised, or there isn't a winner and loser. Reimburse unspent fees proportionally. uint rewardRequester = round.paidFees[uint(Party.Requester)] > 0 ? (round.contributions[_beneficiary][uint(Party.Requester)] * round.feeRewards) / (round.paidFees[uint(Party.Challenger)] + round.paidFees[uint(Party.Requester)]) : 0; uint rewardChallenger = round.paidFees[uint(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint(Party.Challenger)] + round.paidFees[uint(Party.Requester)]) : 0; reward = rewardRequester + rewardChallenger; round.contributions[_beneficiary][uint(Party.Requester)] = 0; round.contributions[_beneficiary][uint(Party.Challenger)] = 0; } else { // Reward the winner. reward = round.paidFees[uint(request.ruling)] > 0 ? (round.contributions[_beneficiary][uint(request.ruling)] * round.feeRewards) / round.paidFees[uint(request.ruling)] : 0; round.contributions[_beneficiary][uint(request.ruling)] = 0; } emit RewardWithdrawal(_betID, _beneficiary, _request, _round, reward); _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Withdraws rewards and reimbursements of multiple rounds at once. This function is O(n) where n is the number of rounds. This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions to the request. * @param _betID The bet index. * @param _request The request from which to withdraw contributions. * @param _cursor The round from where to start withdrawing. * @param _count Rounds greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of rounds, iterates until the last round. */ function batchRoundWithdraw(address payable _beneficiary, uint _betID, uint _request, uint _cursor, uint _count) public { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; for (uint i = _cursor; i<request.rounds.length && (_count==0 || i<_count); i++) withdrawFeesAndRewards(_beneficiary, _betID, _request, i); } /** @dev Withdraws rewards and reimbursements of multiple requests at once. This function is O(n*m) where n is the number of requests and m is the number of rounds. This could exceed gas limits, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions to the request. * @param _betID The bet index. * @param _cursor The request from which to start withdrawing. * @param _count Requests greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of request, iterates until the last request. * @param _roundCursor The round of each request from where to start withdrawing. * @param _roundCount Rounds greater or equal to this value won't be withdrawn. If set to 0 or a value larger than the number of rounds a request has, iteration for that request will stop at the last round. */ function batchRequestWithdraw( address payable _beneficiary, uint _betID, uint _cursor, uint _count, uint _roundCursor, uint _roundCount ) external { Bet storage bet = bets[_betID]; for (uint i = _cursor; i<bet.requests.length && (_count==0 || i<_count); i++) batchRoundWithdraw(_beneficiary, _betID, i, _roundCursor, _roundCount); } /** @dev Executes a request if the challenge period passed and no one challenged the request. * @param _betID The bet index with the request to execute. */ function executeRequest(uint _betID) external { Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; require( now - request.submissionTime > challengePeriodDuration, "Time to challenge the request must have passed." ); require(!request.disputed, "The request should not be disputed."); if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Registered; else if (bet.status == BetStatus.ClearingRequested) bet.status = BetStatus.Absent; else revert("There must be a request."); request.resolved = true; address payable party = address(uint160(request.parties[uint(Party.Requester)])); withdrawFeesAndRewards(party, _betID, bet.requests.length - 1, 0); // Automatically withdraw for the requester. emit BetStatusChange( request.parties[uint(Party.Requester)], address(0x0), _betID, bet.status, false, false ); } /** @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED. * Overrides parent function to account for the situation where the winner loses a case due to paying less appeal fees than expected. * @param _disputeID ID of the dispute in the arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public { Party resultRuling = Party(_ruling); uint _betID = arbitratorDisputeIDToBetID[msg.sender][_disputeID]; Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; Round storage round = request.rounds[request.rounds.length - 1]; require(_ruling <= RULING_OPTIONS); // solium-disable-line error-reason require(address(request.arbitrator) == msg.sender); // solium-disable-line error-reason require(!request.resolved); // solium-disable-line error-reason // The ruling is inverted if the loser paid its fees. if (round.hasPaid[uint(Party.Requester)] == true) // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created. resultRuling = Party.Requester; else if (round.hasPaid[uint(Party.Challenger)] == true) resultRuling = Party.Challenger; emit Ruling(Arbitrator(msg.sender), _disputeID, uint(resultRuling)); executeRuling(_disputeID, uint(resultRuling)); } /** @dev Submit a reference to evidence. EVENT. * @param _betID The bet index. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(uint _betID, string calldata _evidence) external { Bet storage bet = bets[_betID]; Request storage request = bet.requests[bet.requests.length - 1]; require(!request.resolved, "The dispute must not already be resolved."); emit Evidence(request.arbitrator, uint(keccak256(abi.encodePacked(_betID,bet.requests.length - 1))), msg.sender, _evidence); } // ************************ // // * Governance * // // ************************ // /** @dev Change the duration of the challenge period. * @param _challengePeriodDuration The new duration of the challenge period. */ function changeTimeToChallenge(uint _challengePeriodDuration) external onlyGovernor { challengePeriodDuration = _challengePeriodDuration; } /** @dev Change the base amount required as a deposit to make a request. * @param _requesterBaseDeposit The new base amount of wei required to make a request. */ function changeRequesterBaseDeposit(uint _requesterBaseDeposit) external onlyGovernor { requesterBaseDeposit = _requesterBaseDeposit; } /** @dev Change the base amount required as a deposit to challenge a request. * @param _challengerBaseDeposit The new base amount of wei required to challenge a request. */ function changeChallengerBaseDeposit(uint _challengerBaseDeposit) external onlyGovernor { challengerBaseDeposit = _challengerBaseDeposit; } /** @dev Change the governor of the token curated registry. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** @dev Change the address of the goal bet registry contract. * @param _selfCommitmentRegistry The address of the new goal bet registry contract. */ function changeSelfCommitmentRegistry(address _selfCommitmentRegistry) external onlyGovernor { selfCommitmentRegistry = _selfCommitmentRegistry; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by parties when there isn't a winner or loser. * @param _sharedStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeSharedStakeMultiplier(uint _sharedStakeMultiplier) external onlyGovernor { sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by the winner of the previous round. * @param _winnerStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeWinnerStakeMultiplier(uint _winnerStakeMultiplier) external onlyGovernor { winnerStakeMultiplier = _winnerStakeMultiplier; } /** @dev Change the percentage of arbitration fees that must be paid as fee stake by the party that lost the previous round. * @param _loserStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points. */ function changeLoserStakeMultiplier(uint _loserStakeMultiplier) external onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; } /** @dev Change the arbitrator to be used for disputes that may be raised in the next requests. The arbitrator is trusted to support appeal periods and not reenter. * @param _arbitrator The new trusted arbitrator to be used in the next requests. * @param _arbitratorExtraData The extra data used by the new arbitrator. */ function changeArbitrator(Arbitrator _arbitrator, bytes calldata _arbitratorExtraData) external onlyGovernor { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Update the meta evidence used for disputes. * @param _registrationMetaEvidence The meta evidence to be used for future registration request disputes. * @param _clearingMetaEvidence The meta evidence to be used for future clearing request disputes. */ function changeMetaEvidence(string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence) external onlyGovernor { metaEvidenceUpdates++; emit MetaEvidence(2 * metaEvidenceUpdates, _registrationMetaEvidence); emit MetaEvidence(2 * metaEvidenceUpdates + 1, _clearingMetaEvidence); } /* Internal */ /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Make a fee contribution. * @param _round The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. */ function contribute(Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired) internal { // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)])); _round.contributions[_contributor][uint(_side)] += contribution; _round.paidFees[uint(_side)] += contribution; _round.feeRewards += contribution; // Reimburse leftover ETH. _contributor.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. } /** @dev Execute the ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal { uint betID = arbitratorDisputeIDToBetID[msg.sender][_disputeID]; Bet storage bet = bets[betID]; Request storage request = bet.requests[bet.requests.length - 1]; Party winner = Party(_ruling); // Update bet state if (winner == Party.Requester) { // Execute Request if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Registered; else bet.status = BetStatus.Absent; } else { // Revert to previous state. if (bet.status == BetStatus.RegistrationRequested) bet.status = BetStatus.Absent; else if (bet.status == BetStatus.ClearingRequested) bet.status = BetStatus.Registered; } request.resolved = true; request.ruling = Party(_ruling); // Automatically withdraw. if (winner == Party.None) { address payable requester = address(uint160(request.parties[uint(Party.Requester)])); address payable challenger = address(uint160(request.parties[uint(Party.Challenger)])); withdrawFeesAndRewards(requester, betID, bet.requests.length-1, 0); withdrawFeesAndRewards(challenger, betID, bet.requests.length-1, 0); } else { address payable winnerAddr = address(uint160(request.parties[uint(winner)])); withdrawFeesAndRewards(winnerAddr, betID, bet.requests.length-1, 0); } emit BetStatusChange( request.parties[uint(Party.Requester)], request.parties[uint(Party.Challenger)], betID, bet.status, request.disputed, false ); } /* Views */ /** @dev Return true if the bet is on the list. * @param _betID The bet index. * @return allowed True if the address is allowed, false otherwise. */ function isPermitted(uint _betID) external view returns (bool allowed) { Bet storage bet = bets[_betID]; return bet.status == BetStatus.Registered || bet.status == BetStatus.ClearingRequested; } /* Interface Views */ /** @dev Return the sum of withdrawable wei of a request an account is entitled to. This function is O(n), where n is the number of rounds of the request. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _betID The bet index to query. * @param _beneficiary The contributor for which to query. * @param _request The request from which to query for. * @return The total amount of wei available to withdraw. */ function amountWithdrawable(uint _betID, address _beneficiary, uint _request) external view returns (uint total){ Request storage request = bets[_betID].requests[_request]; if (!request.resolved) return total; for (uint i = 0; i < request.rounds.length; i++) { Round storage round = request.rounds[i]; if (!request.disputed || request.ruling == Party.None) { uint rewardRequester = round.paidFees[uint(Party.Requester)] > 0 ? (round.contributions[_beneficiary][uint(Party.Requester)] * round.feeRewards) / (round.paidFees[uint(Party.Requester)] + round.paidFees[uint(Party.Challenger)]) : 0; uint rewardChallenger = round.paidFees[uint(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint(Party.Requester)] + round.paidFees[uint(Party.Challenger)]) : 0; total += rewardRequester + rewardChallenger; } else { total += round.paidFees[uint(request.ruling)] > 0 ? (round.contributions[_beneficiary][uint(request.ruling)] * round.feeRewards) / round.paidFees[uint(request.ruling)] : 0; } } return total; } /** @dev Return the numbers of bets that were submitted. Includes bets that never made it to the list or were later removed. * @return count The numbers of bets in the list. */ function betCount() external view returns (uint count) { return betList.length; } /** @dev Gets the contributions made by a party for a given round of a request. * @param _betID The bet index. * @param _request The position of the request. * @param _round The position of the round. * @param _contributor The address of the contributor. * @return The contributions. */ function getContributions( uint _betID, uint _request, uint _round, address _contributor ) external view returns(uint[3] memory contributions) { Request storage request = bets[_betID].requests[_request]; Round storage round = request.rounds[_round]; contributions = round.contributions[_contributor]; } /** @dev Returns bet information. Includes length of requests array. * @param _betID The queried bet index. * @return The bet information. */ function getBetInfo(uint _betID) external view returns ( BetStatus status, uint numberOfRequests ) { Bet storage bet = bets[_betID]; return ( bet.status, bet.requests.length ); } /** @dev Gets information on a request made for a bet. * @param _betID The queried bet index. * @param _request The request to be queried. * @return The request information. */ function getRequestInfo(uint _betID, uint _request) external view returns ( bool disputed, uint disputeID, uint submissionTime, bool resolved, address[3] memory parties, uint numberOfRounds, Party ruling, Arbitrator arbitratorRequest, bytes memory arbitratorExtraData ) { Request storage request = bets[_betID].requests[_request]; return ( request.disputed, request.disputeID, request.submissionTime, request.resolved, request.parties, request.rounds.length, request.ruling, request.arbitrator, request.arbitratorExtraData ); } /** @dev Gets the information on a round of a request. * @param _betID The queried bet index. * @param _request The request to be queried. * @param _round The round to be queried. * @return The round information. */ function getRoundInfo(uint _betID, uint _request, uint _round) external view returns ( bool appealed, uint[3] memory paidFees, bool[3] memory hasPaid, uint feeRewards ) { Bet storage bet = bets[_betID]; Request storage request = bet.requests[_request]; Round storage round = request.rounds[_round]; return ( _round != (request.rounds.length-1), round.paidFees, round.hasPaid, round.feeRewards ); } } contract SelfCommitment is IArbitrable { using CappedMath for uint; // Operations bounded between 0 and 2**256 - 1. // **************************** // // * Contract variables * // // **************************** // struct Bet { string description; // alias metaevidence uint[3] period; // endBetPeriod, startClaimPeriod, endClaimPeriod uint[2] ratio; // For irrational numbers we assume that the loss of wei is negligible address[3] parties; uint[2] amount; // betterAmount (max), takerTotalAmount mapping(address => uint) amountTaker; bool isPrivate; mapping(address => bool) allowAddress; Arbitrator arbitrator; bytes arbitratorExtraData; uint[3] stakeMultiplier; Status status; // Status of the claim relative to a dispute. uint disputeID; // If dispute exists, the ID of the dispute. Round[] rounds; // Tracks each round of a dispute. Party ruling; // The final ruling given, if any. } struct Round { uint[3] paidFees; // Tracks the fees paid by each side on this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute. mapping(address => uint[3]) contributions; // Maps contributors to their contributions for each side. } Bet[] public bets; // Amount of choices to solve the dispute if needed. uint8 constant AMOUNT_OF_CHOICES = 2; // Enum relative to different periods in the case of a negotiation or dispute. enum Status {NoDispute, WaitingAsker, WaitingTaker, DisputeCreated, Resolved} // The different parties of the dispute. enum Party {None, Asker, Taker} // The different ruling for the dispute resolution. enum RulingOptions {NoRuling, AskerWins, TakerWins} // One-to-one relationship between the dispute and the bet. mapping(address => mapping(uint => uint)) public arbitratorDisputeIDtoBetID; // Settings address public governor; // The address that can make governance changes to the parameters. address public betArbitrableList; uint public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. // **************************** // // * Modifier * // // **************************** // modifier onlyGovernor {require(msg.sender == address(governor), "The caller must be the governor."); _;} // **************************** // // * Events * // // **************************** // /** @dev Indicate that a party has to pay a fee or would otherwise be considered as losing. * @param _transactionID The index of the transaction. * @param _party The party who has to pay. */ event HasToPayFee(uint indexed _transactionID, Party _party); /** @dev To be emitted when a party get the rewards or the deposit. * @param _id The index of the bet. * @param _party The party that paid. * @param _amount The amount paid. */ event Reward(uint indexed _id, Party _party, uint _amount); /** @dev Emitted when a reimbursements and/or contribution rewards are withdrawn. * @param _id The ID of the bet. * @param _contributor The address that sent the contribution. * @param _round The round from which the reward was taken. * @param _value The value of the reward. */ event RewardWithdrawal(uint indexed _id, address indexed _contributor, uint _round, uint _value); /* Constructor */ /** * @dev Constructs the arbitrable token curated registry. * @param _governor The trusted governor of this contract. */ constructor( address _governor ) public { governor = _governor; } // **************************** // // * Contract functions * // // * Modifying the state * // // **************************** // /** @dev To add a new bet. UNTRUSTED. * @param _description The description of the bet. * @param _period The different periods of the bet. * @param _ratio The ratio of the bet. * @param _allowAddress Addresses who are allowed to bet. Empty for all addresses. * @param _arbitrator The arbitrator of the bet. * @param _arbitratorExtraData The configuration for the arbitration. * @param _stakeMultiplier The multipler of the deposit for the different parties. */ function ask( string calldata _description, uint[3] calldata _period, uint[2] calldata _ratio, address[] calldata _allowAddress, Arbitrator _arbitrator, bytes calldata _arbitratorExtraData, uint[3] calldata _stakeMultiplier ) external payable { ArbitrableBetList betArbitrableListInstance = ArbitrableBetList(betArbitrableList); uint totalCost = betArbitrableListInstance.getTotalCost(); require(msg.value > totalCost); require(msg.value - totalCost >= 10000); require(_ratio[0] > 1); require(_ratio[0] > _ratio[1]); require(_period[0] > now); uint amountXratio1 = msg.value * _ratio[0]; // _ratio0 > (_ratio0/_ratio1) require(amountXratio1/msg.value == _ratio[0]); // To prevent multiply overflow. betArbitrableListInstance.requestStatusChange.value(totalCost)(bets.length, msg.sender); Bet storage bet = bets[bets.length++]; bet.parties[1] = msg.sender; bet.description = _description; bet.period = _period; bet.ratio = _ratio; bet.amount = [msg.value - totalCost, 0]; if (_allowAddress.length > 0) { for(uint i; i < _allowAddress.length; i++) bet.allowAddress[_allowAddress[i]] = true; bet.isPrivate = true; } bet.arbitrator = _arbitrator; bet.arbitratorExtraData = _arbitratorExtraData; bet.stakeMultiplier = _stakeMultiplier; } /** @dev To accept a bet. UNTRUSTED. * @param _id The id of the bet. */ function take( uint _id ) external payable { require(msg.value > 0); Bet storage bet = bets[_id]; require(now < bet.period[0], "Should bet before the end period bet."); require(bet.amount[0] > bet.amount[1]); if (bet.isPrivate) require(bet.allowAddress[msg.sender]); address payable taker = msg.sender; // r = bet.ratio[0] / bet.ratio[1] // maxAmountToBet = x / (r-1) - y // maxAmountToBet = x*x / (rx-x) - y uint maxAmountToBet = bet.amount[0]*bet.amount[0] / (bet.ratio[0]*bet.amount[0]/bet.ratio[1] - bet.amount[0]) - bet.amount[1]; uint amountBet = msg.value <= maxAmountToBet ? msg.value : maxAmountToBet; bet.amount[1] += amountBet; bet.amountTaker[taker] = amountBet; if (msg.value > maxAmountToBet) taker.transfer(msg.value - maxAmountToBet); } /** @dev Withdraw the bet if no one took it. TRUSTED. * @param _id The id of the bet. */ function withdraw( uint _id ) external { Bet storage bet = bets[_id]; require(now > bet.period[0], "Should end period bet finished."); if (bet.amount[1] == 0) executeRuling(_id, uint(Party.Asker)); else { uint maxAmountToTake = bet.amount[1] * bet.ratio[0] / bet.ratio[1]; uint amountToAsk = maxAmountToTake - bet.amount[1]; address payable asker = address(uint160(bet.parties[1])); require(bet.amount[0] > amountToAsk); asker.send(bet.amount[0] - amountToAsk); bet.amount[0] = amountToAsk; } } /* Section of Claims or Dispute Resolution */ /** @dev Pay the arbitration fee to claim the bet. To be called by the asker. UNTRUSTED. * Note that the arbitrator can have createDispute throw, * which will make this function throw and therefore lead to a party being timed-out. * This is not a vulnerability as the arbitrator can rule in favor of one party anyway. * @param _id The index of the bet. */ function claimAsker(uint _id) public payable { Bet storage bet = bets[_id]; require( bet.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed." ); require(bet.parties[1] == msg.sender, "The caller must be the creator of the bet."); require(now > bet.period[1], "Should claim after the claim period start."); require(now < bet.period[2], "Should claim before the claim period end."); // Amount required to claim: arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); uint claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); // The asker must cover the claim cost. require(msg.value >= claimCost); if(bet.rounds.length == 0) bet.rounds.length++; Round storage round = bet.rounds[0]; round.hasPaid[uint(Party.Asker)] = true; contribute(round, Party.Asker, msg.sender, msg.value, claimCost); // The taker still has to pay. This can also happen if he has paid, // but arbitrationCost has increased. if (round.paidFees[uint(Party.Taker)] <= claimCost) { bet.status = Status.WaitingTaker; emit HasToPayFee(_id, Party.Taker); } else { // The taker has also paid the fee. We create the dispute raiseDispute(_id, arbitrationCost); } } /** @dev Pay the arbitration fee to claim a bet. To be called by the taker. UNTRUSTED. * @param _id The index of the claim. */ function claimTaker(uint _id) public payable { Bet storage bet = bets[_id]; require( bet.status < Status.DisputeCreated, "Dispute has already been created or because the transaction has been executed." ); // NOTE: We assume that for this smart contract version, // this smart contract is vulnerable to a griefing attack. // We expect a very low ratio of griefing attack // in the majority of cases. require( bet.amountTaker[msg.sender] > 0, "The caller must be the one of the taker." ); require(now > bet.period[1], "Should claim after the claim period start."); require(now < bet.period[2], "Should claim before the claim period end."); bet.parties[2] = msg.sender; // Amount required to claim: arbitration cost + (arbitration cost * multiplier). uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); uint claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); // The taker must cover the claim cost. require(msg.value >= claimCost); if(bet.rounds.length == 0) bet.rounds.length++; Round storage round = bet.rounds[0]; round.hasPaid[uint(Party.Taker)] = true; contribute(round, Party.Taker, msg.sender, msg.value, claimCost); // The taker still has to pay. This can also happen if he has paid, // but arbitrationCost has increased. if (round.paidFees[uint(Party.Taker)] <= claimCost) { bet.status = Status.WaitingAsker; emit HasToPayFee(_id, Party.Taker); } else { // The taker has also paid the fee. We create the dispute. raiseDispute(_id, arbitrationCost); } } /** @dev Make a fee contribution. * @param _round The round to contribute. * @param _side The side for which to contribute. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. */ function contribute( Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired ) internal { // Take up to the amount necessary to fund the current round at the current costs. uint contribution; // Amount contributed. uint remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_side)])); _round.contributions[_contributor][uint(_side)] += contribution; _round.paidFees[uint(_side)] += contribution; _round.feeRewards += contribution; // Reimburse leftover ETH. _contributor.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. } /** @dev Returns the contribution value and remainder from available ETH and required amount. * @param _available The amount of ETH available for the contribution. * @param _requiredAmount The amount of ETH required for the contribution. * @return taken The amount of ETH taken. * @return remainder The amount of ETH left from the contribution. */ function calculateContribution(uint _available, uint _requiredAmount) internal pure returns(uint taken, uint remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Reward asker of the bet if the taker fails to pay the fee. * NOTE: The taker unspent fee are sent to the asker. * @param _id The index of the bet. */ function timeOutByAsker(uint _id) public { Bet storage bet = bets[_id]; require( bet.status == Status.WaitingTaker, "The transaction of the bet must waiting on the taker." ); require( now > bet.period[2], "Timeout claim has not passed yet." ); uint resultRuling = uint(RulingOptions.AskerWins); bet.ruling = Party(resultRuling); executeRuling(_id, resultRuling); } /** @dev Pay taker if the asker fails to pay the fee. * NOTE: The asker unspent fee are sent to the taker. * @param _id The index of the claim. */ function timeOutByTaker(uint _id) public { Bet storage bet = bets[_id]; require( bet.status == Status.WaitingAsker, "The transaction of the bet must waiting on the asker." ); require( now > bet.period[2], "Timeout claim has not passed yet." ); uint resultRuling = uint(RulingOptions.TakerWins); bet.ruling = Party(resultRuling); executeRuling(_id, resultRuling); } /** @dev Create a dispute. UNTRUSTED. * @param _id The index of the bet. * @param _arbitrationCost Amount to pay the arbitrator. */ function raiseDispute(uint _id, uint _arbitrationCost) internal { Bet storage bet = bets[_id]; bet.status = Status.DisputeCreated; uint disputeID = bet.arbitrator.createDispute.value(_arbitrationCost)(AMOUNT_OF_CHOICES, bet.arbitratorExtraData); arbitratorDisputeIDtoBetID[address(bet.arbitrator)][disputeID] = _id; bet.disputeID = disputeID; emit Dispute(bet.arbitrator, bet.disputeID, _id, _id); } /** @dev Submit a reference to evidence. EVENT. * @param _id The index of the claim. * @param _evidence A link to an evidence using its URI. */ function submitEvidence(uint _id, string memory _evidence) public { Bet storage bet = bets[_id]; require( msg.sender == bet.parties[1] || bet.amountTaker[msg.sender] > 0, "The caller must be the asker or a taker." ); require( bet.status >= Status.DisputeCreated, "The dispute has not been created yet." ); emit Evidence(bet.arbitrator, _id, msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded. TRUSTED. * @param _id The ID of the bet with the request to fund. * @param _side The recipient of the contribution. */ function fundAppeal(uint _id, Party _side) external payable { // Recipient must be either the requester or challenger. require(_side == Party.Asker || _side == Party.Taker); // solium-disable-line error-reason Bet storage bet = bets[_id]; require( bet.status >= Status.DisputeCreated, "A dispute must have been raised to fund an appeal." ); (uint appealPeriodStart, uint appealPeriodEnd) = bet.arbitrator.appealPeriod(bet.disputeID); require( now >= appealPeriodStart && now < appealPeriodEnd, "Contributions must be made within the appeal period." ); Round storage round = bet.rounds[bet.rounds.length - 1]; Party winner = Party(bet.arbitrator.currentRuling(bet.disputeID)); Party loser; if (winner == Party.Asker) loser = Party.Taker; else if (winner == Party.Taker) loser = Party.Asker; require(!(_side==loser) || (now-appealPeriodStart < (appealPeriodEnd-appealPeriodStart)/2), "The loser must contribute during the first half of the appeal period."); uint multiplier; if (_side == winner) multiplier = bet.stakeMultiplier[1]; else if (_side == loser) multiplier = bet.stakeMultiplier[2]; else multiplier = bet.stakeMultiplier[0]; uint appealCost = bet.arbitrator.appealCost(bet.disputeID, bet.arbitratorExtraData); uint totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); contribute(round, _side, msg.sender, msg.value, totalCost); if (round.paidFees[uint(_side)] >= totalCost) round.hasPaid[uint(_side)] = true; // Raise appeal if both sides are fully funded. if (round.hasPaid[uint(Party.Taker)] && round.hasPaid[uint(Party.Asker)]) { bet.arbitrator.appeal.value(appealCost)(bet.disputeID, bet.arbitratorExtraData); bet.rounds.length++; round.feeRewards = round.feeRewards.subCap(appealCost); } } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) external { Party resultRuling = Party(_ruling); uint id = arbitratorDisputeIDtoBetID[msg.sender][_disputeID]; Bet storage bet = bets[id]; require(_ruling <= AMOUNT_OF_CHOICES); // solium-disable-line error-reason require(address(bet.arbitrator) == msg.sender); // solium-disable-line error-reason require(bet.status != Status.Resolved); // solium-disable-line error-reason Round storage round = bet.rounds[bet.rounds.length - 1]; // The ruling is inverted if the loser paid its fees. // If one side paid its fees, the ruling is in its favor. // Note that if the other side had also paid, an appeal would have been created. if (round.hasPaid[uint(Party.Asker)] == true) resultRuling = Party.Asker; else if (round.hasPaid[uint(Party.Taker)] == true) resultRuling = Party.Taker; bet.status = Status.Resolved; bet.ruling = resultRuling; emit Ruling(Arbitrator(msg.sender), _disputeID, uint(resultRuling)); executeRuling(id, uint(resultRuling)); } /** @dev Reimburses contributions if no disputes were raised. * If a dispute was raised, sends the fee stake and the reward for the winner. * @param _beneficiary The address that made contributions to a request. * @param _id The ID of the bet. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards( address payable _beneficiary, uint _id, uint _round ) public { Bet storage bet = bets[_id]; Round storage round = bet.rounds[_round]; // The request must be resolved. require(bet.status == Status.Resolved); // solium-disable-line error-reason uint reward; if (!round.hasPaid[uint(Party.Asker)] || !round.hasPaid[uint(Party.Taker)]) { // Reimburse if not enough fees were raised to appeal the ruling. reward = round.contributions[_beneficiary][uint(Party.Asker)] + round.contributions[_beneficiary][uint(Party.Taker)]; round.contributions[_beneficiary][uint(Party.Asker)] = 0; round.contributions[_beneficiary][uint(Party.Taker)] = 0; if(bet.amountTaker[_beneficiary] > 0 && bet.ruling != Party.Asker) { reward += bet.amountTaker[_beneficiary] * bet.ratio[0] / bet.ratio[1]; bet.amountTaker[_beneficiary] = 0; } } else if (bet.ruling == Party.None) { // No disputes were raised, or there isn't a winner and loser. Reimburse unspent fees proportionally. uint rewardAsker = round.paidFees[uint(Party.Asker)] > 0 ? (round.contributions[_beneficiary][uint(Party.Asker)] * round.feeRewards) / (round.paidFees[uint(Party.Taker)] + round.paidFees[uint(Party.Asker)]) : 0; uint rewardTaker = round.paidFees[uint(Party.Taker)] > 0 ? (round.contributions[_beneficiary][uint(Party.Taker)] * round.feeRewards) / (round.paidFees[uint(Party.Taker)] + round.paidFees[uint(Party.Asker)]) : 0; reward = rewardAsker + rewardTaker; round.contributions[_beneficiary][uint(Party.Asker)] = 0; round.contributions[_beneficiary][uint(Party.Taker)] = 0; // Reimburse the fund bet. if(bet.amountTaker[_beneficiary] > 0) { reward += bet.amountTaker[_beneficiary]; bet.amountTaker[_beneficiary] = 0; } } else { // Reward the winner. reward = round.paidFees[uint(bet.ruling)] > 0 ? (round.contributions[_beneficiary][uint(bet.ruling)] * round.feeRewards) / round.paidFees[uint(bet.ruling)] : 0; round.contributions[_beneficiary][uint(bet.ruling)] = 0; if(bet.amountTaker[_beneficiary] > 0 && bet.ruling != Party.Asker) { reward += bet.amountTaker[_beneficiary] * bet.ratio[0] / bet.ratio[1]; bet.amountTaker[_beneficiary] = 0; } } emit RewardWithdrawal(_id, _beneficiary, _round, reward); _beneficiary.send(reward); // It is the user responsibility to accept ETH. } /** @dev Execute a ruling of a dispute. It reimburses the fee to the winning party. * @param _id The index of the bet. * @param _ruling Ruling given by the arbitrator. 1 : Reimburse the owner of the item. 2 : Pay the finder. */ function executeRuling(uint _id, uint _ruling) internal { require(_ruling <= AMOUNT_OF_CHOICES, "Invalid ruling."); Bet storage bet = bets[_id]; bet.status = Status.Resolved; address payable asker = address(uint160(bet.parties[1])); address payable taker = address(uint160(bet.parties[2])); if (_ruling == uint(Party.None)) { if(bet.amount[0] > 0) { asker.send(bet.amount[0]); bet.amount[0] = 0; } if (bet.rounds.length != 0) { withdrawFeesAndRewards(asker, _id, 0); withdrawFeesAndRewards(taker, _id, 0); } } else if (_ruling == uint(Party.Asker)) { require(bet.amount[0] > 0); asker.send(bet.amount[0] + bet.amount[1]); bet.amount[0] = 0; bet.amount[1] = 0; if (bet.rounds.length != 0) withdrawFeesAndRewards(asker, _id, 0); } else { if (bet.rounds.length != 0) withdrawFeesAndRewards(taker, _id, 0); } } /* Governance */ /** @dev Change the governor of the token curated registry. * @param _governor The address of the new governor. */ function changeGovernor(address _governor) external onlyGovernor { governor = _governor; } /** @dev Change the address of the goal bet registry contract. * @param _betArbitrableList The address of the new goal bet registry contract. */ function changeArbitrationBetList(address _betArbitrableList) external onlyGovernor { betArbitrableList = _betArbitrableList; } // **************************** // // * View functions * // // **************************** // /** @dev Get the claim cost * @param _id The index of the claim. */ function getClaimCost(uint _id) external view returns (uint claimCost) { Bet storage bet = bets[_id]; uint arbitrationCost = bet.arbitrator.arbitrationCost(bet.arbitratorExtraData); claimCost = arbitrationCost.addCap((arbitrationCost.mulCap(bet.stakeMultiplier[0])) / MULTIPLIER_DIVISOR); } function getMaxAmountToBet( uint _id ) external view returns (uint maxAmountToBet) { Bet storage bet = bets[_id]; maxAmountToBet = bet.amount[0]*bet.amount[0] / (bet.ratio[0]*bet.amount[0] / bet.ratio[1] - bet.amount[0]) - bet.amount[1]; } /** @dev Return the values of the bets the query finds. This function is O(n), where n is the number of bets. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _cursor The bet index from which to start iterating. To start from either the oldest or newest item. * @param _count The number of bets to return. * @param _filter The filter to use. Each element of the array in sequence means: * - Include absent bets in result. * - Include registered bets in result. * - Include bets with registration requests that are not disputed in result. * - Include bets with clearing requests that are not disputed in result. * - Include disputed bets with registration requests in result. * - Include disputed bets with clearing requests in result. * - Include bets submitted by the caller. * - Include bets challenged by the caller. * - Include bets created. * - Include bets taken. * @return The values of the bets found and whether there are more bets for the current filter and sort. */ function queryBets(uint _cursor, uint _count, bool[10] calldata _filter) external view returns (uint[] memory values, bool hasMore) { values = new uint[](_count); uint index = 0; for ( uint i = _cursor == 0 ? bets.length - 1 : bets.length - 1 - _cursor; i < bets.length; i++ ) { Bet storage bet = bets[i]; ArbitrableBetList betArbitrableListInstance = ArbitrableBetList(betArbitrableList); (ArbitrableBetList.BetStatus arbitrableBetlistStatus, uint numberOfRequests) = betArbitrableListInstance.getBetInfo(i); (bool disputed, , , , address[3] memory parties, , , , ) = betArbitrableListInstance.getRequestInfo(i, numberOfRequests - 1); if ( /* solium-disable operator-whitespace */ (_filter[0] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.Absent) || (_filter[1] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.Registered) || (_filter[2] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.RegistrationRequested && !disputed) || (_filter[3] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.ClearingRequested && !disputed) || (_filter[4] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.RegistrationRequested && disputed) || (_filter[5] && arbitrableBetlistStatus == ArbitrableBetList.BetStatus.ClearingRequested && disputed) || (_filter[6] && parties[1] == msg.sender) || // My Submissions. (_filter[7] && parties[2] == msg.sender) || // My Challenges. (_filter[8] && bet.parties[1] == msg.sender) || // My bets. (_filter[9] && bet.parties[2] == msg.sender) // My taken bets. /* solium-enable operator-whitespace */ ) { if (index < _count) { values[index] = i; index++; } else { hasMore = true; break; } } } } }
* @dev Pay taker if the asker fails to pay the fee. NOTE: The asker unspent fee are sent to the taker. @param _id The index of the claim./
function timeOutByTaker(uint _id) public { Bet storage bet = bets[_id]; require( bet.status == Status.WaitingAsker, "The transaction of the bet must waiting on the asker." ); require( now > bet.period[2], "Timeout claim has not passed yet." ); uint resultRuling = uint(RulingOptions.TakerWins); bet.ruling = Party(resultRuling); executeRuling(_id, resultRuling); }
12,937,031
[ 1, 9148, 268, 6388, 309, 326, 6827, 264, 6684, 358, 8843, 326, 14036, 18, 5219, 30, 1021, 6827, 264, 640, 20693, 14036, 854, 3271, 358, 326, 268, 6388, 18, 225, 389, 350, 1021, 770, 434, 326, 7516, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 813, 1182, 858, 56, 6388, 12, 11890, 389, 350, 13, 1071, 288, 203, 565, 605, 278, 2502, 2701, 273, 324, 2413, 63, 67, 350, 15533, 203, 203, 565, 2583, 12, 203, 1377, 2701, 18, 2327, 422, 2685, 18, 15946, 23663, 264, 16, 203, 1377, 315, 1986, 2492, 434, 326, 2701, 1297, 7336, 603, 326, 6827, 264, 1199, 203, 565, 11272, 203, 565, 2583, 12, 203, 1377, 2037, 405, 2701, 18, 6908, 63, 22, 6487, 203, 1377, 315, 2694, 7516, 711, 486, 2275, 4671, 1199, 203, 565, 11272, 203, 203, 565, 2254, 563, 54, 332, 310, 273, 2254, 12, 54, 332, 310, 1320, 18, 56, 6388, 59, 2679, 1769, 203, 565, 2701, 18, 86, 332, 310, 273, 6393, 93, 12, 2088, 54, 332, 310, 1769, 203, 203, 565, 1836, 54, 332, 310, 24899, 350, 16, 563, 54, 332, 310, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-03-31 */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; contract GemLike { function allowance(address, address) public returns (uint); function approve(address, uint) public; function transfer(address, uint) public returns (bool); function transferFrom(address, address, uint) public returns (bool); } contract ValueLike { function peek() public returns (uint, bool); } contract SaiTubLike { function skr() public view returns (GemLike); function gem() public view returns (GemLike); function gov() public view returns (GemLike); function sai() public view returns (GemLike); function pep() public view returns (ValueLike); function vox() public view returns (VoxLike); function bid(uint) public view returns (uint); function ink(bytes32) public view returns (uint); function tag() public view returns (uint); function tab(bytes32) public returns (uint); function rap(bytes32) public returns (uint); function draw(bytes32, uint) public; function shut(bytes32) public; function exit(uint) public; function give(bytes32, address) public; } contract VoxLike { function par() public returns (uint); } contract JoinLike { function ilk() public returns (bytes32); function gem() public returns (GemLike); function dai() public returns (GemLike); function join(address, uint) public; function exit(address, uint) public; } contract VatLike { function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function hope(address) public; function frob(bytes32, address, address, address, int, int) public; } contract ManagerLike { function vat() public view returns (address); function urns(uint) public view returns (address); function open(bytes32, address) public returns (uint); function frob(uint, int, int) public; function give(uint, address) public; function move(uint, address, uint) public; } contract OtcLike { function getPayAmount(address, address, uint) public view returns (uint); function buyAllAmount(address, uint, address, uint) public; } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ contract ICErc20 { address public underlying; function mint(uint256 mintAmount) external returns (uint); function redeemUnderlying(uint256 redeemAmount) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getCash() external view returns (uint); function supplyRatePerBlock() external view returns (uint); } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { require(_upperBound > 0, "UniformRand/min-bound"); uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (tree.nodes.length == 0) { return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** * @author Brendan Asselstine * @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances. * * Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw. * When a new draw is opened, the previous opened draw is committed. * * The committed balance for an address is the total of their balances for committed Draws. * An address's open balance is their balance in the open Draw. */ library DrawManager { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; using SafeMath for uint256; /** * The ID to use for the selection tree. */ bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws"; uint8 public constant MAX_BRANCHES_PER_NODE = 10; /** * Stores information for all draws. */ struct State { /** * Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index. * There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS. */ SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees; /** * Stores the consolidated draw index that an address deposited to. */ mapping(address => uint256) consolidatedDrawIndices; /** * Stores the last Draw index that an address deposited to. */ mapping(address => uint256) latestDrawIndices; /** * Stores a mapping of Draw index => Draw total */ mapping(uint256 => uint256) __deprecated__drawTotals; /** * The current open Draw index */ uint256 openDrawIndex; /** * The total of committed balances */ uint256 __deprecated__committedSupply; } /** * @notice Opens the next Draw and commits the previous open Draw (if any). * @param self The drawState this library is attached to * @return The index of the new open Draw */ function openNextDraw(State storage self) public returns (uint256) { if (self.openDrawIndex == 0) { // If there is no previous draw, we must initialize self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_BRANCHES_PER_NODE); } else { // else add current draw to sortition sum trees bytes32 drawId = bytes32(self.openDrawIndex); uint256 drawTotal = openSupply(self); self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId); } // now create a new draw uint256 drawIndex = self.openDrawIndex.add(1); self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_BRANCHES_PER_NODE); self.openDrawIndex = drawIndex; return drawIndex; } /** * @notice Deposits the given amount into the current open draw by the given user. * @param self The DrawManager state * @param _addr The address to deposit for * @param _amount The amount to deposit */ function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openDrawIndex = self.openDrawIndex; // update the current draw uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId); currentAmount = currentAmount.add(_amount); drawSet(self, openDrawIndex, currentAmount, _addr); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; // if this is the user's first draw, set it if (consolidatedDrawIndex == 0) { self.consolidatedDrawIndices[_addr] = openDrawIndex; // otherwise, if the consolidated draw is not this draw } else if (consolidatedDrawIndex != openDrawIndex) { // if a second draw does not exist if (latestDrawIndex == 0) { // set the second draw to the current draw self.latestDrawIndices[_addr] = openDrawIndex; // otherwise if a second draw exists but is not the current one } else if (latestDrawIndex != openDrawIndex) { // merge it into the first draw, and update the second draw index to this one uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); uint256 latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(latestAmount), _addr); drawSet(self, latestDrawIndex, 0, _addr); self.latestDrawIndices[_addr] = openDrawIndex; } } } /** * @notice Deposits into a user's committed balance, thereby bypassing the open draw. * @param self The DrawManager state * @param _addr The address of the user for whom to deposit * @param _amount The amount to deposit */ function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; // if they have a committed balance if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(_amount), _addr); } else { // they must not have any committed balance self.latestDrawIndices[_addr] = consolidatedDrawIndex; self.consolidatedDrawIndices[_addr] = self.openDrawIndex.sub(1); drawSet(self, self.consolidatedDrawIndices[_addr], _amount, _addr); } } /** * @notice Withdraws a user's committed and open draws. * @param self The DrawManager state * @param _addr The address whose balance to withdraw */ function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) { uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0) { drawSet(self, consolidatedDrawIndex, 0, _addr); delete self.consolidatedDrawIndices[_addr]; } if (latestDrawIndex != 0) { drawSet(self, latestDrawIndex, 0, _addr); delete self.latestDrawIndices[_addr]; } } /** * @notice Withdraw's from a user's open balance * @param self The DrawManager state * @param _addr The user to withdrawn from * @param _amount The amount to withdraw */ function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId); require(_amount <= openTotal, "DrawMan/exceeds-open"); uint256 remaining = openTotal.sub(_amount); drawSet(self, self.openDrawIndex, remaining, _addr); } /** * @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. * @param self The DrawManager state * @param _addr The user to withdraw from * @param _amount The amount to withdraw. */ function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; uint256 consolidatedAmount = 0; uint256 latestAmount = 0; uint256 total = 0; if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); total = total.add(latestAmount); } if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); total = total.add(consolidatedAmount); } // If the total is greater than zero, then consolidated *must* have the committed balance // However, if the total is zero then the consolidated balance may be the open balance if (total == 0) { return; } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); // if there was a second amount that needs to be updated if (remaining > consolidatedAmount) { uint256 secondRemaining = remaining.sub(consolidatedAmount); drawSet(self, latestDrawIndex, secondRemaining, _addr); } else if (latestAmount > 0) { // else delete the second amount if it exists delete self.latestDrawIndices[_addr]; drawSet(self, latestDrawIndex, 0, _addr); } // if the consolidated amount needs to be destroyed if (remaining == 0) { delete self.consolidatedDrawIndices[_addr]; drawSet(self, consolidatedDrawIndex, 0, _addr); } else if (remaining < consolidatedAmount) { drawSet(self, consolidatedDrawIndex, remaining, _addr); } } /** * @notice Returns the total balance for an address, including committed balances and the open balance. */ function balanceOf(State storage drawState, address _addr) public view returns (uint256) { return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr)); } /** * @notice Returns the total committed balance for an address. * @param self The DrawManager state * @param _addr The address whose committed balance should be returned * @return The total committed balance */ function committedBalanceOf(State storage self, address _addr) public view returns (uint256) { uint256 balance = 0; uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { balance = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), bytes32(uint256(_addr))); } if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), bytes32(uint256(_addr)))); } return balance; } /** * @notice Returns the open balance for an address * @param self The DrawManager state * @param _addr The address whose open balance should be returned * @return The open balance */ function openBalanceOf(State storage self, address _addr) public view returns (uint256) { if (self.openDrawIndex == 0) { return 0; } else { return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr))); } } /** * @notice Returns the open Draw balance for the DrawManager * @param self The DrawManager state * @return The open draw total balance */ function openSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(bytes32(self.openDrawIndex)); } /** * @notice Returns the committed balance for the DrawManager * @param self The DrawManager state * @return The total committed balance */ function committedSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(TREE_OF_DRAWS); } /** * @notice Updates the Draw balance for an address. * @param self The DrawManager state * @param _drawIndex The Draw index * @param _amount The new balance * @param _addr The address whose balance should be updated */ function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal { bytes32 drawId = bytes32(_drawIndex); bytes32 userId = bytes32(uint256(_addr)); uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId); if (oldAmount != _amount) { // If the amount has changed // Update the Draw's balance for that address self.sortitionSumTrees.set(drawId, _amount, userId); // if the draw is committed if (_drawIndex != self.openDrawIndex) { // Get the new draw total uint256 newDrawTotal = self.sortitionSumTrees.total(drawId); // update the draw in the committed tree self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId); } } } /** * @notice Selects an address by indexing into the committed tokens using the passed token. * If there is no committed supply, the zero address is returned. * @param self The DrawManager state * @param _token The token index to select * @return The selected address */ function draw(State storage self, uint256 _token) public view returns (address) { // If there is no one to select, just return the zero address if (committedSupply(self) == 0) { return address(0); } require(_token < committedSupply(self), "Pool/ineligible"); bytes32 drawIndex = self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token); uint256 drawSupply = self.sortitionSumTrees.total(drawIndex); uint256 drawToken = _token % drawSupply; return address(uint256(self.sortitionSumTrees.draw(drawIndex, drawToken))); } /** * @notice Selects an address using the entropy as an index into the committed tokens * The entropy is passed into the UniformRandomNumber library to remove modulo bias. * @param self The DrawManager state * @param _entropy The random entropy to use * @return The selected address */ function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) { uint256 bound = committedSupply(self); address selected; if (bound == 0) { selected = address(0); } else { selected = draw(self, UniformRandomNumber.uniform(uint256(_entropy), bound)); } return selected; } modifier requireOpenDraw(State storage self) { require(self.openDrawIndex > 0, "Pool/no-open"); _; } modifier requireCommittedDraw(State storage self) { require(self.openDrawIndex > 1, "Pool/no-commit"); _; } modifier onlyNonZero(address _addr) { require(_addr != address(0), "Pool/not-zero"); _; } } /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** * @notice Number of positions that the comma is shifted to the right. */ function digits() public pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Test fixed1() equals 10^digits() * Hardcoded to 24 digits. */ function fixed1() public pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * @dev Test mulPrecision() equals sqrt(fixed1) * Hardcoded to 24 digits. */ function mulPrecision() public pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Test maxInt256() equals 2^255 -1 */ function maxInt256() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Test minInt256 equals (2^255) * (-1) */ function minInt256() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev deployment. * Test maxNewFixed() equals maxInt256() / fixed1() * Hardcoded to 24 digits. */ function maxNewFixed() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Minimum value that can be converted to fixed point. Optimize for * deployment. * @dev Test minNewFixed() equals -(maxInt256()) / fixed1() * Hardcoded to 24 digits. */ function minNewFixed() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Test maxFixedAdd() equals maxInt256()-1 / 2 * Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd() * Test add(maxFixedAdd()+1,maxFixedAdd()) throws * Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd() * Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws */ function maxFixedAdd() public pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Test maxFixedSub() equals minInt256() / 2 */ function maxFixedSub() public pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul() * Test multiply(maxFixedMul(),maxFixedMul()+1) throws * Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul() * Test multiply(-maxFixedMul(),maxFixedMul()+1) throws * Hardcoded to 24 digits. */ function maxFixedMul() public pure returns(int256) { return 240615969168004498257251713877715648331380787511296; } /** * @notice Maximum value that can be safely used as a dividend. * @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256(). * Test maxFixedDiv() equals maxInt256()/fixed1() * Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws * Hardcoded to 24 digits. */ function maxFixedDiv() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2) * Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1() * Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws * Hardcoded to 24 digits. */ function maxFixedDivisor() public pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). * @dev Test newFixed(0) returns 0 * Test newFixed(1) returns fixed1() * Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1() * Test newFixed(maxNewFixed()+1) fails */ function newFixed(int256 x) public pure returns (int256) { require(x <= maxNewFixed()); require(x >= minNewFixed()); return x * fixed1(); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) public pure returns (int256) { return x / fixed1(); } /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. * @dev * Test convertFixed(1,0,0) returns 1; * Test convertFixed(1,1,1) returns 1; * Test convertFixed(1,1,0) returns 0; * Test convertFixed(1,0,1) returns 10; * Test convertFixed(10,1,0) returns 1; * Test convertFixed(10,0,1) returns 100; * Test convertFixed(100,1,0) returns 10; * Test convertFixed(100,0,1) returns 1000; * Test convertFixed(1000,2,0) returns 10; * Test convertFixed(1000,0,2) returns 100000; * Test convertFixed(1000,2,1) returns 100; * Test convertFixed(1000,1,2) returns 10000; * Test convertFixed(maxInt256,1,0) returns maxInt256/10; * Test convertFixed(maxInt256,0,1) throws * Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38); * Test convertFixed(1,0,38) returns 10**38; * Test convertFixed(maxInt256,39,0) throws * Test convertFixed(1,0,39) throws */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) public pure returns (int256) { require(_originDigits <= 38 && _destinationDigits <= 38); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 require(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); require(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) public pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) public pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). * @dev * Test newFixedFraction(maxFixedDiv()+1,1) fails * Test newFixedFraction(1,maxFixedDiv()+1) fails * Test newFixedFraction(1,0) fails * Test newFixedFraction(0,1) returns 0 * Test newFixedFraction(1,1) returns fixed1() * Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1() * Test newFixedFraction(1,fixed1()) returns 1 * Test newFixedFraction(1,fixed1()-1) returns 0 */ function newFixedFraction( int256 numerator, int256 denominator ) public pure returns (int256) { require(numerator <= maxNewFixed()); require(denominator <= maxNewFixed()); require(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Returns the integer part of a fixed point number. * @dev * Test integer(0) returns 0 * Test integer(fixed1()) returns fixed1() * Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test integer(-fixed1()) returns -fixed1() * Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1() */ function integer(int256 x) public pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. * @dev * Test fractional(0) returns 0 * Test fractional(fixed1()) returns 0 * Test fractional(fixed1()-1) returns 10^24-1 * Test fractional(-fixed1()) returns 0 * Test fractional(-fixed1()+1) returns -10^24-1 */ function fractional(int256 x) public pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Converts to positive if negative. * Due to int256 having one more negative number than positive numbers * abs(minInt256) reverts. * @dev * Test abs(0) returns 0 * Test abs(fixed1()) returns -fixed1() * Test abs(-fixed1()) returns fixed1() * Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1() */ function abs(int256 x) public pure returns (int256) { if (x >= 0) { return x; } else { int256 result = -x; assert (result > 0); return result; } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. * @dev * Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1 * Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails * Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256() * Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails * Test add(maxInt256(),maxInt256()) fails * Test add(minInt256(),minInt256()) fails */ function add(int256 x, int256 y) public pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) assert(z > x && z > y); if (x < 0 && y < 0) assert(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. * @dev Tests covered by add(x,y) */ function subtract(int256 x, int256 y) public pure returns (int256) { return add(x,-y); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. * @dev * Test multiply(0,0) returns 0 * Test multiply(maxFixedMul(),0) returns 0 * Test multiply(0,maxFixedMul()) returns 0 * Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul() * Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul() * Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5) * Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision()) * Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1) * Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits * Test multiply(maxFixedMul()+1,maxFixedMul()) fails * Test multiply(maxFixedMul(),maxFixedMul()+1) fails */ function multiply(int256 x, int256 y) public pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x * @dev * Test reciprocal(0) fails * Test reciprocal(fixed1()) returns fixed1() * Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated * Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated */ function reciprocal(int256 x) public pure returns (int256) { require(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. * @dev * Test divide(fixed1(),0) fails * Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,1) throws * Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1() */ function divide(int256 x, int256 y) public pure returns (int256) { if (y == fixed1()) return x; require(y != 0); require(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } } /** * @title Blocklock * @author Brendan Asselstine * @notice A time lock with a cooldown period. When locked, the contract will remain locked until it is unlocked manually * or the lock duration expires. After the contract is unlocked, it cannot be locked until the cooldown duration expires. */ library Blocklock { using SafeMath for uint256; struct State { uint256 lockedAt; uint256 unlockedAt; uint256 lockDuration; uint256 cooldownDuration; } /** * @notice Sets the duration of the lock. This how long the lock lasts before it expires and automatically unlocks. * @param self The Blocklock state * @param lockDuration The duration, in blocks, that the lock should last. */ function setLockDuration(State storage self, uint256 lockDuration) public { require(lockDuration > 0, "Blocklock/lock-min"); self.lockDuration = lockDuration; } /** * @notice Sets the cooldown duration in blocks. This is the number of blocks that must pass before being able to * lock again. The cooldown duration begins when the lock duration expires, or when it is unlocked manually. * @param self The Blocklock state * @param cooldownDuration The duration of the cooldown, in blocks. */ function setCooldownDuration(State storage self, uint256 cooldownDuration) public { require(cooldownDuration > 0, "Blocklock/cool-min"); self.cooldownDuration = cooldownDuration; } /** * @notice Returns whether the state is locked at the given block number. * @param self The Blocklock state * @param blockNumber The current block number. */ function isLocked(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt != 0 && blockNumber >= self.lockedAt && blockNumber < endAt ); } /** * @notice Locks the state at the given block number. * @param self The Blocklock state * @param blockNumber The block number to use as the lock start time */ function lock(State storage self, uint256 blockNumber) public { require(canLock(self, blockNumber), "Blocklock/no-lock"); self.lockedAt = blockNumber; } /** * @notice Manually unlocks the lock. * @param self The Blocklock state * @param blockNumber The block number at which the lock is being unlocked. */ function unlock(State storage self, uint256 blockNumber) public { self.unlockedAt = blockNumber; } /** * @notice Returns whether the Blocklock can be locked at the given block number * @param self The Blocklock state * @param blockNumber The block number to check against * @return True if we can lock at the given block number, false otherwise. */ function canLock(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt == 0 || blockNumber >= endAt.add(self.cooldownDuration) ); } function cooldownEndAt(State storage self) internal view returns (uint256) { return lockEndAt(self).add(self.cooldownDuration); } function lockEndAt(State storage self) internal view returns (uint256) { uint256 endAt = self.lockedAt.add(self.lockDuration); // if we unlocked early if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) { endAt = self.unlockedAt; } return endAt; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Implementation of the {IERC777} interface. * * Largely taken from the OpenZeppelin ERC777 contract. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. * * It is important to note that no Mint events are emitted. Tokens are minted in batches * by a state change in a tree data structure, so emitting a Mint event for each user * is not possible. * */ contract PoolToken is Initializable, IERC20, IERC777 { using SafeMath for uint256; using Address for address; /** * Event emitted when a user or operator redeems tokens */ event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777Token") bytes32 constant internal TOKENS_INTERFACE_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; // keccak256("ERC20Token") bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH = 0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a; string internal _name; string internal _symbol; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] internal _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) internal _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) internal _operators; mapping(address => mapping(address => bool)) internal _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) internal _allowances; // The Pool that is bound to this token BasePool internal _pool; /** * @notice Initializes the PoolToken. * @param name The name of the token * @param symbol The token symbol * @param defaultOperators The default operators who are allowed to move tokens */ function init ( string memory name, string memory symbol, address[] memory defaultOperators, BasePool pool ) public initializer { require(bytes(name).length != 0, "PoolToken/name"); require(bytes(symbol).length != 0, "PoolToken/symbol"); require(address(pool) != address(0), "PoolToken/pool-zero"); _name = name; _symbol = symbol; _pool = pool; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this)); } /** * @notice Returns the address of the Pool contract * @return The address of the pool contract */ function pool() public view returns (BasePool) { return _pool; } /** * @notice Calls the ERC777 transfer hook, and emits Redeemed and Transfer. Can only be called by the Pool contract. * @param from The address from which to redeem tokens * @param amount The amount of tokens to redeem */ function poolRedeem(address from, uint256 amount) external onlyPool { _callTokensToSend(from, from, address(0), amount, '', ''); emit Redeemed(from, from, amount, '', ''); emit Transfer(from, address(0), amount); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public view returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _pool.committedSupply(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address _addr) external view returns (uint256) { return _pool.committedBalanceOf(_addr); } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, recipient, amount, data, ""); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/transfer-zero"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev Allows a user to withdraw their tokens as the underlying asset. * * Also emits a {Transfer} event for ERC20 compatibility. */ function redeem(uint256 amount, bytes calldata data) external { _redeem(msg.sender, msg.sender, amount, data, ""); } /** * @dev See {IERC777-burn}. Not currently implemented. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(msg.sender != operator, "PoolToken/auth-self"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != msg.sender, "PoolToken/revoke-self"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator"); _send(msg.sender, sender, recipient, amount, data, operatorData); } /** * @dev See {IERC777-operatorBurn}. * * Currently not supported */ function operatorBurn(address, uint256, bytes calldata, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user. * * Emits {Redeemed} and {Transfer} events. */ function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, account), "PoolToken/not-operator"); _redeem(msg.sender, account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = msg.sender; _approve(holder, spender, value); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "PoolToken/negative")); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/to-zero"); require(holder != address(0), "PoolToken/from-zero"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * Called by the associated Pool to emit `Mint` events. * @param amount The amount that was minted */ function poolMint(uint256 amount) external onlyPool { _mintEvents(address(_pool), address(_pool), amount, '', ''); } /** * Emits {Minted} and {IERC20-Transfer} events. */ function _mintEvents( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); require(to != address(0), "PoolToken/to-zero"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, false); } /** * @dev Redeems tokens for the underlying asset. * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to redeem * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _redeem( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _pool.withdrawCommittedDepositFrom(from, amount); emit Redeemed(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } /** * @notice Moves tokens from one user to another. Emits Sent and Transfer events. */ function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _pool.moveCommitted(from, to, amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * Approves of a token spend by a spender for a holder. * @param holder The address from which the tokens are spent * @param spender The address that is spending the tokens * @param value The amount of tokens to spend */ function _approve(address holder, address spender, uint256 value) private { require(spender != address(0), "PoolToken/from-zero"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal notLocked { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck whether to require that, if the recipient is a contract, it has registered a IERC777Recipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "PoolToken/no-recip-inter"); } } /** * @notice Requires the sender to be the pool contract */ modifier onlyPool() { require(msg.sender == address(_pool), "PoolToken/only-pool"); _; } /** * @notice Requires the contract to be unlocked */ modifier notLocked() { require(!_pool.isLocked(), "PoolToken/is-locked"); _; } } /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract BasePool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; using Blocklock for Blocklock.State; bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1)); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("PoolTogetherRewardListener") bytes32 constant internal REWARD_LISTENER_INTERFACE_HASH = 0x68f03b0b1a978ee238a70b362091d993343460bc1a2830ab3f708936d9f564a4; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when a user deposits into the Pool and the deposit is immediately committed * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event DepositedAndCommitted(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws their sponsorship and fees from the pool. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their open deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event OpenDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their committed deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event CommittedDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when an address collects a fee * @param sender The address collecting the fee * @param amount The fee amount * @param drawId The draw from which the fee was awarded */ event FeeCollected(address indexed sender, uint256 amount, uint256 drawId); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when a RewardListener call fails * @param drawId The draw id * @param winner The address that one the draw * @param impl The implementation address of the RewardListener */ event RewardListenerFailed( uint256 indexed drawId, address indexed winner, address indexed impl ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event DepositsPaused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event DepositsUnpaused(address indexed sender); /** * Emitted when the draw is rolled over in the event that the secret is forgotten. */ event RolledOver(uint256 indexed drawId); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; bytes32 entropy; address winner; uint256 netWinnings; uint256 fee; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) internal balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) internal draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State internal drawState; /** * A structure containing the administrators */ Roles.Role internal admins; /** * Whether the contract is paused */ bool public paused; Blocklock.State internal blocklock; PoolToken public poolToken; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 _lockDuration, uint256 _cooldownDuration ) public initializer { require(_owner != address(0), "Pool/owner-zero"); require(_cToken != address(0), "Pool/ctoken-zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); initBlocklock(_lockDuration, _cooldownDuration); } function setPoolToken(PoolToken _poolToken) external onlyAdmin { require(address(poolToken) == address(0), "Pool/token-was-set"); require(address(_poolToken.pool()) == address(this), "Pool/token-mismatch"); poolToken = _poolToken; } function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal { blocklock.setLockDuration(_lockDuration); blocklock.setCooldownDuration(_cooldownDuration); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw( nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash, bytes32(0), address(0), uint256(0), uint256(0) ); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Emits the Committed event for the current open draw. */ function emitCommitted() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); if (address(poolToken) != address(0)) { poolToken.poolMint(openSupply()); } } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin { if (currentCommittedDrawId() > 0) { require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward"); } if (currentOpenDrawId() != 0) { emitCommitted(); } open(nextSecretHash); } /** * @notice Ignores the current draw, and opens the next draw. * @dev This function will be removed once the winner selection has been decentralized. * @param nextSecretHash The hash to commit for the next draw */ function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. * @param _salt The salt that was used to conceal the secret */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin { reward(lastSecret, _salt); openNextDraw(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw * @param _salt The salt that was used to conceal the secret */ function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant { // require that there is a committed draw // require that the committed draw has not been rewarded uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret"); // derive entropy from the revealed secret bytes32 entropy = keccak256(abi.encodePacked(_secret)); _reward(drawId, draw, entropy); } function _reward(uint256 drawId, Draw storage draw, bytes32 entropy) internal { blocklock.unlock(block.number); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings; // It's possible when the APR is zero that the underlying balance will be slightly lower than the accountedBalance // due to rounding errors in the Compound contract. if (underlyingBalance > accountedBalance) { grossWinnings = capWinnings(underlyingBalance.sub(accountedBalance)); } // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); draw.winner = winningAddress; draw.netWinnings = netWinnings; draw.fee = fee; draw.entropy = entropy; // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Updated the accounted total accountedBalance = underlyingBalance; // Update balance of the winner balances[winningAddress] = balances[winningAddress].add(netWinnings); // Enter their winnings into the open draw drawState.deposit(winningAddress, netWinnings); callRewarded(winningAddress, netWinnings, drawId); } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); emit FeeCollected(draw.feeBeneficiary, fee, drawId); } /** * @notice Calls the reward listener for the winner, if a listener exists. * @dev Checks for a listener using the ERC1820 registry. The listener is given a gas stipend of 200,000 to run the function. * The number 200,000 was selected because it's safely above the gas requirements for PoolTogether [Pod](https://github.com/pooltogether/pods) contract. * * @param winner The winner. If they have a listener registered in the ERC1820 registry it will be called. * @param netWinnings The amount that was won. * @param drawId The draw id that was won. */ function callRewarded(address winner, uint256 netWinnings, uint256 drawId) internal { address impl = ERC1820_REGISTRY.getInterfaceImplementer(winner, REWARD_LISTENER_INTERFACE_HASH); if (impl != address(0)) { (bool success,) = impl.call.gas(200000)(abi.encodeWithSignature("rewarded(address,uint256,uint256)", winner, netWinnings, drawId)); if (!success) { emit RewardListenerFailed(drawId, winner, impl); } } } /** * @notice A function that skips the reward for the committed draw id. * @dev This function will be removed once the entropy is decentralized. */ function rollover() public onlyAdmin requireCommittedNoReward { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER; emit RolledOver( drawId ); emit Rewarded( drawId, address(0), ROLLED_OVER_ENTROPY_MAGIC_NUMBER, 0, 0 ); } /** * @notice Ensures that the winnings don't overflow. Note that we can make this integer max, because the fee * is always less than zero (meaning the FixidityLib.multiply will always make the number smaller) */ function capWinnings(uint256 _grossWinnings) internal pure returns (uint256) { uint256 max = uint256(FixidityLib.maxNewFixed()); if (_grossWinnings > max) { return max; } return _grossWinnings; } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); // _feeFraction *must* be less than 1 ether, so it will never overflow int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public unlessDepositsPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the sponsorship amount _depositSponsorshipFrom(msg.sender, _amount); } /** * @notice Deposits the token balance for this contract as a sponsorship. * If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship. */ function transferBalanceToSponsorship() public unlessDepositsPaused { // Deposit the sponsorship amount _depositSponsorshipFrom(address(this), token().balanceOf(address(this))); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw unlessDepositsPaused nonReentrant notLocked { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the funds _depositPoolFrom(msg.sender, _amount); } /** * @notice Deposits sponsorship for a user * @param _spender The user who is sponsoring * @param _amount The amount they are sponsoring */ function _depositSponsorshipFrom(address _spender, uint256 _amount) internal { // Deposit the funds _depositFrom(_spender, _amount); emit SponsorshipDeposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit will be open until the next draw is committed. * @param _spender The user who is depositing * @param _amount The amount the user is depositing */ function _depositPoolFrom(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.deposit(_spender, _amount); _depositFrom(_spender, _amount); emit Deposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit is made part of the currently committed draw * @param _spender The user who is depositing * @param _amount The amount to deposit */ function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked { // Update the user's eligibility drawState.depositCommitted(_spender, _amount); _depositFrom(_spender, _amount); emit DepositedAndCommitted(_spender, _amount); } /** * @notice Deposits into the pool for a user. Updates their balance and transfers their tokens into this contract. * @param _spender The user who is depositing * @param _amount The amount they are depositing */ function _depositFrom(address _spender, uint256 _amount) internal { // Update the user's balance balances[_spender] = balances[_spender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "Pool/approve"); require(cToken.mint(_amount) == 0, "Pool/supply"); } /** * Withdraws the given amount from the user's deposits. It first withdraws from their sponsorship, * then their open deposits, then their committed deposits. * * @param amount The amount to withdraw. */ function withdraw(uint256 amount) public nonReentrant notLocked { uint256 remainingAmount = amount; // first sponsorship uint256 sponsorshipAndFeesBalance = sponsorshipAndFeeBalanceOf(msg.sender); if (sponsorshipAndFeesBalance < remainingAmount) { withdrawSponsorshipAndFee(sponsorshipAndFeesBalance); remainingAmount = remainingAmount.sub(sponsorshipAndFeesBalance); } else { withdrawSponsorshipAndFee(remainingAmount); return; } // now pending uint256 pendingBalance = drawState.openBalanceOf(msg.sender); if (pendingBalance < remainingAmount) { _withdrawOpenDeposit(msg.sender, pendingBalance); remainingAmount = remainingAmount.sub(pendingBalance); } else { _withdrawOpenDeposit(msg.sender, remainingAmount); return; } // now committed. remainingAmount should not be greater than committed balance. _withdrawCommittedDeposit(msg.sender, remainingAmount); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant notLocked { uint256 committedBalance = drawState.committedBalanceOf(msg.sender); uint256 balance = balances[msg.sender]; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(msg.sender, balance); if (address(poolToken) != address(0)) { poolToken.poolRedeem(msg.sender, committedBalance); } emit Withdrawn(msg.sender, balance); } /** * Withdraws only from the sender's sponsorship and fee balances * @param _amount The amount to withdraw */ function withdrawSponsorshipAndFee(uint256 _amount) public { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee"); _withdraw(msg.sender, _amount); emit SponsorshipAndFeesWithdrawn(msg.sender, _amount); } /** * Returns the total balance of the user's sponsorship and fees * @param _sender The user whose balance should be returned */ function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) { return balances[_sender].sub(drawState.balanceOf(_sender)); } /** * Withdraws from the user's open deposits * @param _amount The amount to withdraw */ function withdrawOpenDeposit(uint256 _amount) public nonReentrant notLocked { _withdrawOpenDeposit(msg.sender, _amount); } function _withdrawOpenDeposit(address sender, uint256 _amount) internal { drawState.withdrawOpen(sender, _amount); _withdraw(sender, _amount); emit OpenDepositWithdrawn(sender, _amount); } /** * Withdraws from the user's committed deposits * @param _amount The amount to withdraw */ function withdrawCommittedDeposit(uint256 _amount) public nonReentrant notLocked returns (bool) { _withdrawCommittedDeposit(msg.sender, _amount); return true; } function _withdrawCommittedDeposit(address sender, uint256 _amount) internal { _withdrawCommittedDepositAndEmit(sender, _amount); if (address(poolToken) != address(0)) { poolToken.poolRedeem(sender, _amount); } } /** * Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token. * @param _from The user to withdraw from * @param _amount The amount to withdraw */ function withdrawCommittedDepositFrom( address _from, uint256 _amount ) external onlyToken notLocked returns (bool) { return _withdrawCommittedDepositAndEmit(_from, _amount); } /** * A function that withdraws committed deposits for a user and emits the corresponding events. * @param _from User to withdraw for * @param _amount The amount to withdraw */ function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) { drawState.withdrawCommitted(_from, _amount); _withdraw(_from, _amount); emit CommittedDepositWithdrawn(_from, _amount); return true; } /** * @notice Allows the associated PoolToken to move committed tokens from one user to another. * @param _from The account to move tokens from * @param _to The account that is receiving the tokens * @param _amount The amount of tokens to transfer */ function moveCommitted( address _from, address _to, uint256 _amount ) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) { balances[_from] = balances[_from].sub(_amount, "move could not sub amount"); balances[_to] = balances[_to].add(_amount); drawState.withdrawCommitted(_from, _amount); drawState.depositCommitted(_to, _amount); return true; } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(address _sender, uint256 _amount) internal { uint256 balance = balances[_sender]; require(_amount <= balance, "Pool/no-funds"); // Update the user's balance balances[_sender] = balance.sub(_amount); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem"); require(token().transfer(_sender, _amount), "Pool/transfer"); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (drawState.openDrawIndex > 1) { return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Returns whether the current committed draw has been rewarded * @return True if the current committed draw has been rewarded, false otherwise */ function currentCommittedDrawHasBeenRewarded() internal view returns (bool) { Draw storage draw = draws[currentCommittedDrawId()]; return draw.entropy != bytes32(0); } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. * entropy: the entropy used to select the winner * winner: the address of the winner * netWinnings: the total winnings less the fee * fee: the fee taken by the beneficiary */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash, bytes32 entropy, address winner, uint256 netWinnings, uint256 fee ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; entropy = draw.entropy; winner = draw.winner; netWinnings = draw.netWinnings; fee = draw.fee; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) external view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits. * @param _addr The address of the user to check. * @return The user's current balance. */ function totalBalanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Returns a user's committed balance. This is the balance of their Pool tokens. * @param _addr The address of the user to check. * @return The user's current balance. */ function balanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply(); } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction <= 1 ether, "Pool/less-1"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } /** * @notice Sets the fee beneficiary for subsequent Draws. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "Pool/not-zero"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * Admins cannot remove themselves. This ensures there is always one admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "Pool/no-admin"); require(_admin != msg.sender, "Pool/remove-self"); admins.remove(_admin); emit AdminRemoved(_admin); } /** * Requires that there is a committed draw that has not been rewarded. */ modifier requireCommittedNoReward() { require(currentCommittedDrawId() > 0, "Pool/committed"); require(!currentCommittedDrawHasBeenRewarded(), "Pool/already"); _; } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() public view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /** * @notice Locks the movement of tokens (essentially the committed deposits and winnings) * @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes. */ function lockTokens() public onlyAdmin { blocklock.lock(block.number); } /** * @notice Unlocks the movement of tokens (essentially the committed deposits) */ function unlockTokens() public onlyAdmin { blocklock.unlock(block.number); } /** * Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue * to collect rewards and withdraw, but eventually the Pool will grow smaller. * * emits DepositsPaused */ function pauseDeposits() public unlessDepositsPaused onlyAdmin { paused = true; emit DepositsPaused(msg.sender); } /** * @notice Unpauses all deposits into the contract * * emits DepositsUnpaused */ function unpauseDeposits() public whenDepositsPaused onlyAdmin { paused = false; emit DepositsUnpaused(msg.sender); } /** * @notice Check if the contract is locked. * @return True if the contract is locked, false otherwise */ function isLocked() public view returns (bool) { return blocklock.isLocked(block.number); } /** * @notice Returns the block number at which the lock expires * @return The block number at which the lock expires */ function lockEndAt() public view returns (uint256) { return blocklock.lockEndAt(); } /** * @notice Check cooldown end block * @return The block number at which the cooldown ends and the contract can be re-locked */ function cooldownEndAt() public view returns (uint256) { return blocklock.cooldownEndAt(); } /** * @notice Returns whether the contract can be locked * @return True if the contract can be locked, false otherwise */ function canLock() public view returns (bool) { return blocklock.canLock(block.number); } /** * @notice Duration of the lock * @return Returns the duration of the lock in blocks. */ function lockDuration() public view returns (uint256) { return blocklock.lockDuration; } /** * @notice Returns the cooldown duration. The cooldown period starts after the Pool has been unlocked. * The Pool cannot be locked during the cooldown period. * @return The cooldown duration in blocks */ function cooldownDuration() public view returns (uint256) { return blocklock.cooldownDuration; } /** * @notice requires the pool not to be locked */ modifier notLocked() { require(!blocklock.isLocked(block.number), "Pool/locked"); _; } /** * @notice requires the pool to be locked */ modifier onlyLocked() { require(blocklock.isLocked(block.number), "Pool/unlocked"); _; } /** * @notice requires the caller to be an admin */ modifier onlyAdmin() { require(admins.has(msg.sender), "Pool/admin"); _; } /** * @notice Requires an open draw to exist */ modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "Pool/no-open"); _; } /** * @notice Requires deposits to be paused */ modifier whenDepositsPaused() { require(paused, "Pool/d-not-paused"); _; } /** * @notice Requires deposits not to be paused */ modifier unlessDepositsPaused() { require(!paused, "Pool/d-paused"); _; } /** * @notice Requires the caller to be the pool token */ modifier onlyToken() { require(msg.sender == address(poolToken), "Pool/only-token"); _; } /** * @notice requires the passed user's committed balance to be greater than or equal to the passed amount * @param _from The user whose committed balance should be checked * @param _amount The minimum amount they must have */ modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) { uint256 committedBalance = drawState.committedBalanceOf(_from); require(_amount <= committedBalance, "not enough funds"); _; } } contract ScdMcdMigration { SaiTubLike public tub; VatLike public vat; ManagerLike public cdpManager; JoinLike public saiJoin; JoinLike public wethJoin; JoinLike public daiJoin; constructor( address tub_, // SCD tub contract address address cdpManager_, // MCD manager contract address address saiJoin_, // MCD SAI collateral adapter contract address address wethJoin_, // MCD ETH collateral adapter contract address address daiJoin_ // MCD DAI adapter contract address ) public { tub = SaiTubLike(tub_); cdpManager = ManagerLike(cdpManager_); vat = VatLike(cdpManager.vat()); saiJoin = JoinLike(saiJoin_); wethJoin = JoinLike(wethJoin_); daiJoin = JoinLike(daiJoin_); require(wethJoin.gem() == tub.gem(), "non-matching-weth"); require(saiJoin.gem() == tub.sai(), "non-matching-sai"); tub.gov().approve(address(tub), uint(-1)); tub.skr().approve(address(tub), uint(-1)); tub.sai().approve(address(tub), uint(-1)); tub.sai().approve(address(saiJoin), uint(-1)); wethJoin.gem().approve(address(wethJoin), uint(-1)); daiJoin.dai().approve(address(daiJoin), uint(-1)); vat.hope(address(daiJoin)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } // Function to swap SAI to DAI // This function is to be used by users that want to get new DAI in exchange of old one (aka SAI) // wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one) function swapSaiToDai( uint wad ) external { // Get wad amount of SAI from user's wallet: saiJoin.gem().transferFrom(msg.sender, address(this), wad); // Join the SAI wad amount to the `vat`: saiJoin.join(address(this), wad); // Lock the SAI wad amount to the CDP and generate the same wad amount of DAI vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad)); // Send DAI wad amount as a ERC20 token to the user's wallet daiJoin.exit(msg.sender, wad); } // Function to swap DAI to SAI // This function is to be used by users that want to get SAI in exchange of DAI // wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP function swapDaiToSai( uint wad ) external { // Get wad amount of DAI from user's wallet: daiJoin.dai().transferFrom(msg.sender, address(this), wad); // Join the DAI wad amount to the vat: daiJoin.join(address(this), wad); // Payback the DAI wad amount and unlocks the same value of SAI collateral vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad)); // Send SAI wad amount as a ERC20 token to the user's wallet saiJoin.exit(msg.sender, wad); } // Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage. // In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio) function migrate( bytes32 cup ) external returns (uint cdp) { // Get values uint debtAmt = tub.tab(cup); // CDP SAI debt uint pethAmt = tub.ink(cup); // CDP locked collateral uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH // Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio // This is not actually a problem as this ilk will only be accessed by this migration contract, // which will make sure to have the amounts balanced out at the end of the execution. vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), -toInt(debtAmt), 0 ); saiJoin.exit(address(this), debtAmt); // SAI is exited as a token // Shut SAI CDP and gets WETH back tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call) tub.exit(pethAmt); // Converts PETH to WETH // Open future user's CDP in MCD cdp = cdpManager.open(wethJoin.ilk(), address(this)); // Join WETH to Adapter wethJoin.join(cdpManager.urns(cdp), ethAmt); // Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP (, uint rate,,,) = vat.ilks(wethJoin.ilk()); cdpManager.frob( cdp, toInt(ethAmt), toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt ); // Move DAI generated to migration contract (to recover the used funds) cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27)); // Re-balance MCD SAI migration contract's CDP vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), 0, -toInt(debtAmt) ); // Set ownership of CDP to the user cdpManager.give(cdp, msg.sender); } } /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @title MCDAwarePool * @author Brendan Asselstine [email protected] * @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to * detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai * and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for * users to encourage them to migrate to the MCD Pool. */ contract MCDAwarePool is BasePool, IERC777Recipient { IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; uint256 internal constant DEFAULT_LOCK_DURATION = 40; uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80; /** * @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts) */ ScdMcdMigration public scdMcdMigration; /** * @notice The address of the Sai Pool contract */ MCDAwarePool public saiPool; /** * @notice Initializes the contract. * @param _owner The initial administrator of the contract * @param _cToken The Compound cToken to bind this Pool to * @param _feeFraction The fraction of the winnings to give to the beneficiary * @param _feeBeneficiary The beneficiary who receives the fee */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 lockDuration, uint256 cooldownDuration ) public initializer { super.init( _owner, _cToken, _feeFraction, _feeBeneficiary, lockDuration, cooldownDuration ); initRegistry(); initBlocklock(lockDuration, cooldownDuration); } /** * @notice Used to initialize the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock. */ function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public { initRegistry(); if (blocklock.lockDuration == 0) { initBlocklock(lockDuration, cooldownDuration); } } function initRegistry() internal { ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin { _initMigration(_scdMcdMigration, _saiPool); } function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal { require(address(scdMcdMigration) == address(0), "Pool/init"); require(address(_scdMcdMigration) != address(0), "Pool/mig-def"); scdMcdMigration = _scdMcdMigration; saiPool = _saiPool; // may be null } /** * @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool * and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of * the sender. It will reject all other tokens. * * If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the * open prize. This is to encourage migration. * * @param from The sender * @param amount The amount they are transferring */ function tokensReceived( address, // operator address from, address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface uint256 amount, bytes calldata, bytes calldata ) external unlessDepositsPaused { require(msg.sender == address(saiPoolToken()), "Pool/sai-only"); require(address(token()) == address(daiToken()), "Pool/not-dai"); // cash out of the Pool. This call transfers sai to this contract saiPoolToken().redeem(amount, ''); // approve of the transfer to the migration contract saiToken().approve(address(scdMcdMigration), amount); // migrate the sai to dai. The contract now has dai scdMcdMigration.swapSaiToDai(amount); if (currentCommittedDrawId() > 0) { // now deposit the dai as tickets _depositPoolFromCommitted(from, amount); } else { _depositPoolFrom(from, amount); } } /** * @notice Returns the address of the PoolSai pool token contract * @return The address of the Sai PoolToken contract */ function saiPoolToken() internal view returns (PoolToken) { if (address(saiPool) != address(0)) { return saiPool.poolToken(); } else { return PoolToken(0); } } /** * @notice Returns the address of the Sai token * @return The address of the sai token */ function saiToken() public returns (GemLike) { return scdMcdMigration.saiJoin().gem(); } /** * @notice Returns the address of the Dai token * @return The address of the Dai token. */ function daiToken() public returns (GemLike) { return scdMcdMigration.daiJoin().dai(); } }
* @notice Ignores the current draw, and opens the next draw. @dev This function will be removed once the winner selection has been decentralized. @param nextSecretHash The hash to commit for the next draw/
function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); }
8,015,386
[ 1, 45, 1600, 3485, 326, 783, 3724, 16, 471, 10400, 326, 1024, 3724, 18, 225, 1220, 445, 903, 506, 3723, 3647, 326, 5657, 1224, 4421, 711, 2118, 2109, 12839, 1235, 18, 225, 1024, 5207, 2310, 1021, 1651, 358, 3294, 364, 326, 1024, 3724, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 10643, 21896, 1876, 3678, 2134, 6493, 12, 3890, 1578, 1024, 5207, 2310, 13, 1071, 1338, 4446, 288, 203, 565, 10643, 21896, 5621, 203, 565, 1696, 2134, 6493, 12, 4285, 5207, 2310, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xe01ba6c593003b0edcd43b7839a7c36b00a44dfc //Contract name: SBITokenCrowdsale //Balance: 0.029 Ether //Verification Date: 6/15/2018 //Transacion Count: 6 // CODE STARTS HERE pragma solidity ^0.4.19; contract CrowdsaleParameters { /////////////////////////////////////////////////////////////////////////// // Production Config /////////////////////////////////////////////////////////////////////////// // ICO period timestamps: // 1524182400 = April 20, 2018. // 1529452800 = June 20, 2018. uint256 public constant generalSaleStartDate = 1524182400; uint256 public constant generalSaleEndDate = 1529452800; /////////////////////////////////////////////////////////////////////////// // QA Config /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Configuration Independent Parameters /////////////////////////////////////////////////////////////////////////// struct AddressTokenAllocation { address addr; uint256 amount; } AddressTokenAllocation internal generalSaleWallet = AddressTokenAllocation(0x5aCdaeF4fa410F38bC26003d0F441d99BB19265A, 22800000); AddressTokenAllocation internal bounty = AddressTokenAllocation(0xc1C77Ff863bdE913DD53fD6cfE2c68Dfd5AE4f7F, 2000000); AddressTokenAllocation internal partners = AddressTokenAllocation(0x307744026f34015111B04ea4D3A8dB9FdA2650bb, 3200000); AddressTokenAllocation internal team = AddressTokenAllocation(0xCC4271d219a2c33a92aAcB4C8D010e9FBf664D1c, 12000000); AddressTokenAllocation internal featureDevelopment = AddressTokenAllocation(0x06281A31e1FfaC1d3877b29150bdBE93073E043B, 0); } contract Owned { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * Constructor * * Sets contract owner to address of constructor caller */ function Owned() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } /** * Change Owner * * Changes ownership of this contract. Only owner can call this method. * * @param newOwner - new owner's address */ function changeOwner(address newOwner) onlyOwner public { require(newOwner != address(0)); require(newOwner != owner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract SBIToken is Owned, CrowdsaleParameters { using SafeMath for uint256; /* Public variables of the token */ string public standard = 'ERC20/SBI'; string public name = 'Subsoil Blockchain Investitions'; string public symbol = 'SBI'; uint8 public decimals = 18; /* Arrays of all balances */ mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; mapping (address => mapping (address => bool)) private allowanceUsed; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Issuance(uint256 _amount); // triggered when the total supply is increased event Destruction(uint256 _amount); // triggered when the total supply is decreased event NewSBIToken(address _token); /* Miscellaneous */ uint256 public totalSupply = 0; // 40000000; bool public transfersEnabled = true; /** * Constructor * * Initializes contract with initial supply tokens to the creator of the contract */ function SBIToken() public { owner = msg.sender; mintToken(generalSaleWallet); mintToken(bounty); mintToken(partners); mintToken(team); emit NewSBIToken(address(this)); } modifier transfersAllowed { require(transfersEnabled); _; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } /** * 1. Associate crowdsale contract address with this Token * 2. Allocate general sale amount * * @param _crowdsaleAddress - crowdsale contract address */ function approveCrowdsale(address _crowdsaleAddress) external onlyOwner { approveAllocation(generalSaleWallet, _crowdsaleAddress); } function approveAllocation(AddressTokenAllocation tokenAllocation, address _crowdsaleAddress) internal { uint uintDecimals = decimals; uint exponent = 10**uintDecimals; uint amount = tokenAllocation.amount * exponent; allowed[tokenAllocation.addr][_crowdsaleAddress] = amount; emit Approval(tokenAllocation.addr, _crowdsaleAddress, amount); } /** * Get token balance of an address * * @param _address - address to query * @return Token balance of _address */ function balanceOf(address _address) public constant returns (uint256 balance) { return balances[_address]; } /** * Get token amount allocated for a transaction from _owner to _spender addresses * * @param _owner - owner address, i.e. address to transfer from * @param _spender - spender address, i.e. address to transfer to * @return Remaining amount allowed to be transferred */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Send coins from sender's address to address specified in parameters * * @param _to - address to send to * @param _value - amount to send in Wei */ function transfer(address _to, uint256 _value) public transfersAllowed onlyPayloadSize(2*32) returns (bool success) { 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; } /** * Create token and credit it to target address * Created tokens need to vest * */ function mintToken(AddressTokenAllocation tokenAllocation) internal { uint uintDecimals = decimals; uint exponent = 10**uintDecimals; uint mintedAmount = tokenAllocation.amount * exponent; // Mint happens right here: Balance becomes non-zero from zero balances[tokenAllocation.addr] += mintedAmount; totalSupply += mintedAmount; // Emit Issue and Transfer events emit Issuance(mintedAmount); emit Transfer(address(this), tokenAllocation.addr, mintedAmount); } /** * Allow another contract to spend some tokens on your behalf * * @param _spender - address to allocate tokens for * @param _value - number of tokens to allocate * @return True in case of success, otherwise false */ function approve(address _spender, uint256 _value) public onlyPayloadSize(2*32) returns (bool success) { require(_value == 0 || allowanceUsed[msg.sender][_spender] == false); allowed[msg.sender][_spender] = _value; allowanceUsed[msg.sender][_spender] = false; emit Approval(msg.sender, _spender, _value); return true; } /** * A contract attempts to get the coins. Tokens should be previously allocated * * @param _to - address to transfer tokens to * @param _from - address to transfer tokens from * @param _value - number of tokens to transfer * @return True in case of success, otherwise false */ function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed onlyPayloadSize(3*32) returns (bool success) { 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; } /** * Default method * * This unnamed function is called whenever someone tries to send ether to * it. Just revert transaction because there is nothing that Token can do * with incoming ether. * * Missing payable modifier prevents accidental sending of ether */ function() public {} /** * Enable or disable transfers * * @param _enable - True = enable, False = disable */ function toggleTransfers(bool _enable) external onlyOwner { transfersEnabled = _enable; } } contract SBITokenCrowdsale is Owned, CrowdsaleParameters { using SafeMath for uint256; string public name = 'Subsoil Blockchain Investitions Crowdsale'; /* Token and records */ SBIToken private token; address public bank; address saleWalletAddress; uint private tokenMultiplier = 10; uint public totalCollected = 0; uint public saleStartTimestamp; uint public saleStopTimestamp; uint public saleGoal; bool public goalReached = false; uint public preicoTokensPerEth = 27314; uint public tokensPerEth = 10500; mapping (address => uint256) private investmentRecords; address crowdsaleAddress = this; uint256 public constant saleStartDate = 1530403200; uint256 public constant saleEndDate = 1535759940; uint256 public constant preSaleStartDate = 1529020800; uint256 public constant preSaleEndDate = 1530403140; uint public preSaleAmount = 5800000; /* Events */ event TokenSale(address indexed tokenReceiver, uint indexed etherAmount, uint indexed tokenAmount, uint tokensPerEther); event FundTransfer(address indexed from, address indexed to, uint indexed amount); /** * Constructor * * @param _tokenAddress - address of token (deployed before this contract) */ function SBITokenCrowdsale(address _tokenAddress, address _bankAddress) public { token = SBIToken(_tokenAddress); bank = _bankAddress; tokenMultiplier = tokenMultiplier ** token.decimals(); saleWalletAddress = generalSaleWallet.addr; // Initialize sale goal saleGoal = generalSaleWallet.amount; } /** * Is sale active * * @return active - True, if sale is active */ function isICOActive() public constant returns (bool active) { active = ((preSaleStartDate <= now) && (now <= saleEndDate) && (!goalReached)); return active; } /* eth rate is very volatile */ function setTokenRate(uint rate) public onlyOwner { tokensPerEth = rate; } /** * Process received payment * * Determine the integer number of tokens that was purchased considering current * stage, tier bonus, and remaining amount of tokens in the sale wallet. * Transfer purchased tokens to investorAddress and return unused portion of * ether (change) * * @param investorAddress - address that ether was sent from * @param amount - amount of Wei received */ function processPayment(address investorAddress, uint amount) internal { require(isICOActive()); assert(msg.value > 0 finney); // Fund transfer event emit FundTransfer(investorAddress, address(this), amount); uint remainingTokenBalance = token.balanceOf(saleWalletAddress) / tokenMultiplier; // Calculate token amount that is purchased, // truncate to integer uint tokensRate = 0; uint tokenAmount = 0; uint acceptedAmount = 0; uint mainTokens = 0; uint discountTokens = 0; if (preSaleStartDate <= now && now <= preSaleEndDate && remainingTokenBalance > 17000000) { tokensRate = preicoTokensPerEth; discountTokens = remainingTokenBalance - 17000000; uint acceptedPreicoAmount = discountTokens * 1e18 / preicoTokensPerEth; // 212 uint acceptedMainAmount = 17000000 * 1e18 / tokensPerEth; // 1619 acceptedAmount = acceptedPreicoAmount + acceptedMainAmount; if (acceptedPreicoAmount < amount) { mainTokens = (amount - acceptedPreicoAmount) * tokensPerEth / 1e18; tokenAmount = discountTokens + mainTokens; } else { tokenAmount = preicoTokensPerEth * amount / 1e18; } } else { tokensRate = tokensPerEth; tokenAmount = amount * tokensPerEth / 1e18; acceptedAmount = remainingTokenBalance * tokensPerEth * 1e18; } // Check that stage wallet has enough tokens. If not, sell the rest and // return change. if (remainingTokenBalance <= tokenAmount) { tokenAmount = remainingTokenBalance; goalReached = true; } // Transfer tokens to baker and return ETH change token.transferFrom(saleWalletAddress, investorAddress, tokenAmount * tokenMultiplier); emit TokenSale(investorAddress, amount, tokenAmount, tokensRate); // Return change if (amount > acceptedAmount) { uint change = amount - acceptedAmount; investorAddress.transfer(change); emit FundTransfer(address(this), investorAddress, change); } // Update crowdsale performance investmentRecords[investorAddress] += acceptedAmount; totalCollected += acceptedAmount; } /** * Transfer ETH amount from contract to bank's address. */ function safeWithdrawal() external onlyOwner { bank.transfer(crowdsaleAddress.balance); emit FundTransfer(crowdsaleAddress, bank, crowdsaleAddress.balance); } /** * Default method * * Processes all ETH that it receives and credits SBI tokens to sender * according to current stage bonus */ function () external payable { processPayment(msg.sender, msg.value); } /** * Kill method * * Destructs this contract */ function kill() external onlyOwner { require(!isICOActive()); if (crowdsaleAddress.balance > 0) { revert(); } if (now < preSaleStartDate) { selfdestruct(owner); } // save the not sold tokens to featureDevelopment wallet uint featureDevelopmentAmount = token.balanceOf(saleWalletAddress); // Transfer tokens to baker and return ETH change token.transferFrom(saleWalletAddress, featureDevelopment.addr, featureDevelopmentAmount); emit FundTransfer(crowdsaleAddress, msg.sender, crowdsaleAddress.balance); selfdestruct(owner); } }
* Process received payment Determine the integer number of tokens that was purchased considering current stage, tier bonus, and remaining amount of tokens in the sale wallet. Transfer purchased tokens to investorAddress and return unused portion of ether (change) @param investorAddress - address that ether was sent from @param amount - amount of Wei received/ Fund transfer event Calculate token amount that is purchased, truncate to integer Check that stage wallet has enough tokens. If not, sell the rest and return change. Return change
function processPayment(address investorAddress, uint amount) internal { require(isICOActive()); assert(msg.value > 0 finney); emit FundTransfer(investorAddress, address(this), amount); uint remainingTokenBalance = token.balanceOf(saleWalletAddress) / tokenMultiplier; uint tokensRate = 0; uint tokenAmount = 0; uint acceptedAmount = 0; uint mainTokens = 0; uint discountTokens = 0; if (preSaleStartDate <= now && now <= preSaleEndDate && remainingTokenBalance > 17000000) { tokensRate = preicoTokensPerEth; discountTokens = remainingTokenBalance - 17000000; acceptedAmount = acceptedPreicoAmount + acceptedMainAmount; if (acceptedPreicoAmount < amount) { mainTokens = (amount - acceptedPreicoAmount) * tokensPerEth / 1e18; tokenAmount = discountTokens + mainTokens; tokenAmount = preicoTokensPerEth * amount / 1e18; } tokensRate = tokensPerEth; tokenAmount = amount * tokensPerEth / 1e18; acceptedAmount = remainingTokenBalance * tokensPerEth * 1e18; } if (remainingTokenBalance <= tokenAmount) { tokenAmount = remainingTokenBalance; goalReached = true; } emit TokenSale(investorAddress, amount, tokenAmount, tokensRate); if (amount > acceptedAmount) { uint change = amount - acceptedAmount; investorAddress.transfer(change); emit FundTransfer(address(this), investorAddress, change); } totalCollected += acceptedAmount; }
6,405,171
[ 1, 2227, 5079, 5184, 225, 10229, 326, 3571, 1300, 434, 2430, 716, 1703, 5405, 343, 8905, 24453, 783, 225, 6009, 16, 17742, 324, 22889, 16, 471, 4463, 3844, 434, 2430, 316, 326, 272, 5349, 9230, 18, 225, 12279, 5405, 343, 8905, 2430, 358, 2198, 395, 280, 1887, 471, 327, 10197, 14769, 434, 225, 225, 2437, 261, 3427, 13, 225, 2198, 395, 280, 1887, 300, 1758, 716, 225, 2437, 1703, 3271, 628, 225, 3844, 300, 3844, 434, 1660, 77, 5079, 19, 478, 1074, 7412, 871, 9029, 1147, 3844, 716, 353, 5405, 343, 8905, 16, 10310, 358, 3571, 2073, 716, 6009, 9230, 711, 7304, 2430, 18, 971, 486, 16, 357, 80, 326, 3127, 471, 327, 2549, 18, 2000, 2549, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1207, 6032, 12, 2867, 2198, 395, 280, 1887, 16, 2254, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 291, 2871, 51, 3896, 10663, 203, 3639, 1815, 12, 3576, 18, 1132, 405, 374, 574, 82, 402, 1769, 203, 203, 3639, 3626, 478, 1074, 5912, 12, 5768, 395, 280, 1887, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 3639, 2254, 4463, 1345, 13937, 273, 1147, 18, 12296, 951, 12, 87, 5349, 16936, 1887, 13, 342, 1147, 23365, 31, 203, 203, 203, 3639, 2254, 2430, 4727, 273, 374, 31, 203, 3639, 2254, 1147, 6275, 273, 374, 31, 203, 3639, 2254, 8494, 6275, 273, 374, 31, 203, 3639, 2254, 2774, 5157, 273, 374, 31, 203, 3639, 2254, 12137, 5157, 273, 374, 31, 203, 203, 3639, 309, 261, 1484, 30746, 22635, 1648, 2037, 597, 2037, 1648, 675, 30746, 24640, 597, 4463, 1345, 13937, 405, 8043, 9449, 13, 288, 203, 1850, 2430, 4727, 273, 675, 10764, 5157, 2173, 41, 451, 31, 203, 1850, 12137, 5157, 273, 4463, 1345, 13937, 300, 8043, 9449, 31, 203, 203, 1850, 8494, 6275, 273, 8494, 1386, 10764, 6275, 397, 8494, 6376, 6275, 31, 203, 203, 1850, 309, 261, 23847, 1386, 10764, 6275, 411, 3844, 13, 288, 203, 5411, 2774, 5157, 273, 261, 8949, 300, 8494, 1386, 10764, 6275, 13, 380, 2430, 2173, 41, 451, 342, 404, 73, 2643, 31, 203, 5411, 1147, 6275, 273, 12137, 5157, 397, 2774, 5157, 31, 203, 5411, 1147, 6275, 273, 675, 10764, 5157, 2173, 41, 451, 380, 3844, 342, 404, 73, 2643, 31, 203, 1850, 289, 203, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-11-08 */ // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.6.7 https://hardhat.org // File contracts/Math/Math.sol /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/Common/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 GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File 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 contracts/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory __name, string memory __symbol) public { _name = __name; _symbol = __symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of `from`'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of `from`'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/Curve/IveFXS.sol pragma abicoder v2; interface IveFXS { struct LockedBalance { int128 amount; uint256 end; } function commit_transfer_ownership(address addr) external; function apply_transfer_ownership() external; function commit_smart_wallet_checker(address addr) external; function apply_smart_wallet_checker() external; function toggleEmergencyUnlock() external; function recoverERC20(address token_addr, uint256 amount) external; function get_last_user_slope(address addr) external view returns (int128); function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256); function locked__end(address _addr) external view returns (uint256); function checkpoint() external; function deposit_for(address _addr, uint256 _value) external; function create_lock(uint256 _value, uint256 _unlock_time) external; function increase_amount(uint256 _value) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; function balanceOf(address addr) external view returns (uint256); function balanceOf(address addr, uint256 _t) external view returns (uint256); function balanceOfAt(address addr, uint256 _block) external view returns (uint256); function totalSupply() external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupplyAt(uint256 _block) external view returns (uint256); function totalFXSSupply() external view returns (uint256); function totalFXSSupplyAt(uint256 _block) external view returns (uint256); function changeController(address _newController) external; function token() external view returns (address); function supply() external view returns (uint256); function locked(address addr) external view returns (LockedBalance memory); function epoch() external view returns (uint256); function point_history(uint256 arg0) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_history(address arg0, uint256 arg1) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_epoch(address arg0) external view returns (uint256); function slope_changes(uint256 arg0) external view returns (int128); function controller() external view returns (address); function transfersEnabled() external view returns (bool); function emergencyUnlockActive() external view returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function version() external view returns (string memory); function decimals() external view returns (uint256); function future_smart_wallet_checker() external view returns (address); function smart_wallet_checker() external view returns (address); function admin() external view returns (address); function future_admin() external view returns (address); } // File contracts/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/Uniswap/TransferHelper.sol // 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 contracts/Uniswap_V3/pool/IUniswapV3PoolImmutables.sol /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // File contracts/Uniswap_V3/pool/IUniswapV3PoolState.sol /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // File contracts/Uniswap_V3/pool/IUniswapV3PoolDerivedState.sol /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // File contracts/Uniswap_V3/pool/IUniswapV3PoolActions.sol /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // File contracts/Uniswap_V3/pool/IUniswapV3PoolOwnerActions.sol /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // File contracts/Uniswap_V3/pool/IUniswapV3PoolEvents.sol /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // File contracts/Uniswap_V3/IUniswapV3Pool.sol /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // File contracts/Misc_AMOs/gelato/IGUniPool.sol interface IGUniPool { function mint(uint256 mintAmount, address receiver) external returns ( uint256 amount0, uint256 amount1, uint128 liquidityMinted ); function burn(uint256 burnAmount, address receiver) external returns ( uint256 amount0, uint256 amount1, uint128 liquidityBurned ); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function upperTick() external view returns (int24); function lowerTick() external view returns (int24); function pool() external view returns (IUniswapV3Pool); function decimals() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function getMintAmounts(uint256 amount0Max, uint256 amount1Max) external view returns ( uint256 amount0, uint256 amount1, uint256 mintAmount ); function getUnderlyingBalances() external view returns (uint256 amount0, uint256 amount1); function getPositionID() external view returns (bytes32 positionID); } // File contracts/Misc_AMOs/stakedao/IOpynPerpVault.sol interface IOpynPerpVault { function BASE() external view returns (uint256); function BASE_COINS(uint256) external view returns (address); function actions(uint256) external view returns (address); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function cap() external view returns (uint256); function closePositions() external; function curveLPToken() external view returns (address); function curveMetaZap() external view returns (address); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function depositCrvLP(uint256 amount) external; function depositUnderlying(uint256 amount, uint256 minCrvLPToken, uint256 indexOfAsset) external; function emergencyPause() external; function feeRecipient() external view returns (address); function getSharesByDepositAmount(uint256 _amount) external view returns (uint256); function getWithdrawAmountByShares(uint256 _shares) external view returns (uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function name() external view returns (string memory); function owner() external view returns (address); function renounceOwnership() external; function resumeFromPause() external; function rollOver(uint256[] memory _allocationPercentages) external; function sdTokenAddress() external view returns (address); function setActions(address[] memory _actions) external; function setCap(uint256 _newCap) external; function setWithdrawReserve(uint256 _reserve) external; function setWithdrawalFeePercentage(uint256 _newWithdrawalFeePercentage) external; function setWithdrawalFeeRecipient(address _newWithdrawalFeeRecipient) external; function state() external view returns (uint8); function stateBeforePause() external view returns (uint8); function symbol() external view returns (string memory); function totalStakedaoAsset() external view returns (uint256); function totalSupply() external view returns (uint256); function totalUnderlyingControlled() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transferOwnership(address newOwner) external; function wantedAsset() external view returns (address); function withdrawCrvLp(uint256 _share) external; function withdrawReserve() external view returns (uint256); function withdrawUnderlying(uint256 _share, uint256 _minUnderlying) external; function withdrawalFeePercentage() external view returns (uint256); } // File contracts/Curve/IFraxGaugeController.sol // https://github.com/swervefi/swerve/edit/master/packages/swerve-contracts/interfaces/IGaugeController.sol interface IFraxGaugeController { struct Point { uint256 bias; uint256 slope; } struct VotedSlope { uint256 slope; uint256 power; uint256 end; } // Public variables function admin() external view returns (address); function future_admin() external view returns (address); function token() external view returns (address); function voting_escrow() external view returns (address); function n_gauge_types() external view returns (int128); function n_gauges() external view returns (int128); function gauge_type_names(int128) external view returns (string memory); function gauges(uint256) external view returns (address); function vote_user_slopes(address, address) external view returns (VotedSlope memory); function vote_user_power(address) external view returns (uint256); function last_user_vote(address, address) external view returns (uint256); function points_weight(address, uint256) external view returns (Point memory); function time_weight(address) external view returns (uint256); function points_sum(int128, uint256) external view returns (Point memory); function time_sum(uint256) external view returns (uint256); function points_total(uint256) external view returns (uint256); function time_total() external view returns (uint256); function points_type_weight(int128, uint256) external view returns (uint256); function time_type_weight(uint256) external view returns (uint256); // Getter functions function gauge_types(address) external view returns (int128); function gauge_relative_weight(address) external view returns (uint256); function gauge_relative_weight(address, uint256) external view returns (uint256); function get_gauge_weight(address) external view returns (uint256); function get_type_weight(int128) external view returns (uint256); function get_total_weight() external view returns (uint256); function get_weights_sum_per_type(int128) external view returns (uint256); // External functions function commit_transfer_ownership(address) external; function apply_transfer_ownership() external; function add_gauge( address, int128, uint256 ) external; function checkpoint() external; function checkpoint_gauge(address) external; function global_emission_rate() external view returns (uint256); function gauge_relative_weight_write(address) external returns (uint256); function gauge_relative_weight_write(address, uint256) external returns (uint256); function add_type(string memory, uint256) external; function change_type_weight(int128, uint256) external; function change_gauge_weight(address, uint256) external; function change_global_emission_rate(uint256) external; function vote_for_gauge_weights(address, uint256) external; } // File contracts/Curve/IFraxGaugeFXSRewardsDistributor.sol interface IFraxGaugeFXSRewardsDistributor { function acceptOwnership() external; function curator_address() external view returns(address); function currentReward(address gauge_address) external view returns(uint256 reward_amount); function distributeReward(address gauge_address) external returns(uint256 weeks_elapsed, uint256 reward_tally); function distributionsOn() external view returns(bool); function gauge_whitelist(address) external view returns(bool); function is_middleman(address) external view returns(bool); function last_time_gauge_paid(address) external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function owner() external view returns(address); function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function setCurator(address _new_curator_address) external; function setGaugeController(address _gauge_controller_address) external; function setGaugeState(address _gauge_address, bool _is_middleman, bool _is_active) external; function setTimelock(address _new_timelock) external; function timelock_address() external view returns(address); function toggleDistributions() external; } // File contracts/Utils/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/Staking/StakingRewardsMultiGauge.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ===================== StakingRewardsMultiGauge ===================== // ==================================================================== // veFXS-enabled // Multiple tokens with different reward rates can be emitted // Multiple teams can set the reward rates for their token(s) // Those teams can also use a gauge, or an external function with // Apes together strong // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Saddle Team: https://github.com/saddle-finance // Fei Team: https://github.com/fei-protocol // Alchemix Team: https://github.com/alchemix-finance // Liquity Team: https://github.com/liquity // Gelato Team (kassandraoftroy): https://github.com/gelatodigital // Originally inspired by Synthetix.io, but heavily modified by the Frax team // https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol // -------------------- VARIES -------------------- // G-UNI // mStable // import '../Misc_AMOs/mstable/IFeederPool.sol'; // StakeDAO sdETH-FraxPut // StakeDAO Vault // import '../Misc_AMOs/stakedao/IStakeDaoVault.sol'; // Uniswap V2 // import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; // ------------------------------------------------ // Inheritance contract StakingRewardsMultiGauge is Owned, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances IveFXS private veFXS = IveFXS(0xc8418aF6358FFddA74e09Ca9CC3Fe03Ca6aDC5b0); // -------------------- VARIES -------------------- // G-UNI // IGUniPool public stakingToken; // mStable // IFeederPool public stakingToken; // sdETH-FraxPut Vault IOpynPerpVault public stakingToken; // StakeDAO Vault // IStakeDaoVault public stakingToken; // Uniswap V2 // IUniswapV2Pair public stakingToken; // ------------------------------------------------ IFraxGaugeFXSRewardsDistributor public rewards_distributor; // FRAX address private constant frax_address = 0x853d955aCEf822Db058eb8505911ED77F175b99e; // Constant for various precisions uint256 private constant MULTIPLIER_PRECISION = 1e18; // Time tracking uint256 public periodFinish; uint256 public lastUpdateTime; // Lock time and multiplier settings uint256 public lock_max_multiplier = uint256(3e18); // E18. 1x = e18 uint256 public lock_time_for_max_multiplier = 3 * 365 * 86400; // 3 years uint256 public lock_time_min = 86400; // 1 * 86400 (1 day) // veFXS related uint256 public vefxs_per_frax_for_max_boost = uint256(4e18); // E18. 4e18 means 4 veFXS must be held by the staker per 1 FRAX uint256 public vefxs_max_multiplier = uint256(2e18); // E18. 1x = 1e18 mapping(address => uint256) private _vefxsMultiplierStored; // Reward addresses, gauge addresses, reward rates, and reward managers mapping(address => address) public rewardManagers; // token addr -> manager addr address[] public rewardTokens; address[] public gaugeControllers; uint256[] public rewardRatesManual; string[] public rewardSymbols; mapping(address => uint256) public rewardTokenAddrToIdx; // token addr -> token index // Reward period uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days) // Reward tracking uint256[] private rewardsPerTokenStored; mapping(address => mapping(uint256 => uint256)) private userRewardsPerTokenPaid; // staker addr -> token id -> paid amount mapping(address => mapping(uint256 => uint256)) private rewards; // staker addr -> token id -> reward amount mapping(address => uint256) private lastRewardClaimTime; // staker addr -> timestamp uint256[] private last_gauge_relative_weights; uint256[] private last_gauge_time_totals; // Balance tracking uint256 private _total_liquidity_locked; uint256 private _total_combined_weight; mapping(address => uint256) private _locked_liquidity; mapping(address => uint256) private _combined_weights; // List of valid migrators (set by governance) mapping(address => bool) public valid_migrators; // Stakers set which migrator(s) they want to use mapping(address => mapping(address => bool)) public staker_allowed_migrators; // Uniswap V2 (or G-UNI) ONLY bool frax_is_token0; // Stake tracking mapping(address => LockedStake[]) private lockedStakes; // Greylisting of bad addresses mapping(address => bool) public greylist; // Administrative booleans bool public stakesUnlocked; // Release locked stakes in case of emergency bool public migrationsOn; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals bool public withdrawalsPaused; // For emergencies bool public rewardsCollectionPaused; // For emergencies bool public stakingPaused; // For emergencies /* ========== STRUCTS ========== */ struct LockedStake { bytes32 kek_id; uint256 start_timestamp; uint256 liquidity; uint256 ending_timestamp; uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000 } /* ========== MODIFIERS ========== */ modifier onlyByOwner() { require(msg.sender == owner, "Not the owner"); _; } modifier onlyTknMgrs(address reward_token_address) { require(msg.sender == owner || isTokenManagerFor(msg.sender, reward_token_address), "Not owner or tkn mgr"); _; } modifier isMigrating() { require(migrationsOn == true, "Not in migration"); _; } modifier notStakingPaused() { require(stakingPaused == false, "Staking paused"); _; } modifier updateRewardAndBalance(address account, bool sync_too) { _updateRewardAndBalance(account, sync_too); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address _stakingToken, address _rewards_distributor_address, string[] memory _rewardSymbols, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRatesManual, address[] memory _gaugeControllers ) Owned(_owner){ // -------------------- VARIES -------------------- // G-UNI // stakingToken = IGUniPool(_stakingToken); // address token0 = address(stakingToken.token0()); // frax_is_token0 = token0 == frax_address; // mStable // stakingToken = IFeederPool(_stakingToken); // StakeDAO sdETH-FraxPut Vault stakingToken = IOpynPerpVault(_stakingToken); // StakeDAO Vault // stakingToken = IStakeDaoVault(_stakingToken); // Uniswap V2 // stakingToken = IUniswapV2Pair(_stakingToken); // address token0 = stakingToken.token0(); // if (token0 == frax_address) frax_is_token0 = true; // else frax_is_token0 = false; // ------------------------------------------------ rewards_distributor = IFraxGaugeFXSRewardsDistributor(_rewards_distributor_address); rewardTokens = _rewardTokens; gaugeControllers = _gaugeControllers; rewardRatesManual = _rewardRatesManual; rewardSymbols = _rewardSymbols; for (uint256 i = 0; i < _rewardTokens.length; i++){ // For fast token address -> token ID lookups later rewardTokenAddrToIdx[_rewardTokens[i]] = i; // Initialize the stored rewards rewardsPerTokenStored.push(0); // Initialize the reward managers rewardManagers[_rewardTokens[i]] = _rewardManagers[i]; // Push in empty relative weights to initialize the array last_gauge_relative_weights.push(0); // Push in empty time totals to initialize the array last_gauge_time_totals.push(0); } // Other booleans stakesUnlocked = false; // Initialization lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); } /* ========== VIEWS ========== */ // Total locked liquidity tokens function totalLiquidityLocked() external view returns (uint256) { return _total_liquidity_locked; } // Locked liquidity for a given account function lockedLiquidityOf(address account) external view returns (uint256) { return _locked_liquidity[account]; } // Total 'balance' used for calculating the percent of the pool the account owns // Takes into account the locked stake time multiplier function totalCombinedWeight() external view returns (uint256) { return _total_combined_weight; } // Combined weight for a specific account function combinedWeightOf(address account) external view returns (uint256) { return _combined_weights[account]; } function fraxPerLPToken() public view returns (uint256) { // Get the amount of FRAX 'inside' of the lp tokens uint256 frax_per_lp_token; // G-UNI // ============================================ // { // (uint256 reserve0, uint256 reserve1) = stakingToken.getUnderlyingBalances(); // uint256 total_frax_reserves = frax_is_token0 ? reserve0 : reserve1; // frax_per_lp_token = total_frax_reserves.mul(1e18).div(stakingToken.totalSupply()); // } // mStable // ============================================ // { // uint256 total_frax_reserves; // (, IFeederPool.BassetData memory vaultData) = (stakingToken.getBasset(frax_address)); // total_frax_reserves = uint256(vaultData.vaultBalance); // frax_per_lp_token = total_frax_reserves.mul(1e18).div(stakingToken.totalSupply()); // } // StakeDAO sdETH-FraxPut Vault // ============================================ { uint256 frax3crv_held = stakingToken.totalUnderlyingControlled(); // Optimistically assume 50/50 FRAX/3CRV ratio in the metapool to save gas frax_per_lp_token = (frax3crv_held.mul(1e18).div(stakingToken.totalSupply())) / 2; } // StakeDAO Vault // ============================================ // { // uint256 frax3crv_held = stakingToken.balance(); // // // Optimistically assume 50/50 FRAX/3CRV ratio in the metapool to save gas // frax_per_lp_token = (frax3crv_held.mul(1e18).div(stakingToken.totalSupply())) / 2; // } // Uniswap V2 // ============================================ // { // uint256 total_frax_reserves; // (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves()); // if (frax_is_token0) total_frax_reserves = reserve0; // else total_frax_reserves = reserve1; // frax_per_lp_token = total_frax_reserves.mul(1e18).div(stakingToken.totalSupply()); // } return frax_per_lp_token; } function userStakedFrax(address account) public view returns (uint256) { return (fraxPerLPToken()).mul(_locked_liquidity[account]).div(1e18); } function minVeFXSForMaxBoost(address account) public view returns (uint256) { return (userStakedFrax(account)).mul(vefxs_per_frax_for_max_boost).div(MULTIPLIER_PRECISION); } function veFXSMultiplier(address account) public view returns (uint256) { // The claimer gets a boost depending on amount of veFXS they have relative to the amount of FRAX 'inside' // of their locked LP tokens uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (veFXS.balanceOf(account)).mul(MULTIPLIER_PRECISION).div(veFXS_needed_for_max_boost); uint256 vefxs_multiplier = ((user_vefxs_fraction).mul(vefxs_max_multiplier)).div(MULTIPLIER_PRECISION); // Cap the boost to the vefxs_max_multiplier if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier; return vefxs_multiplier; } else return 0; // This will happen with the first stake, when user_staked_frax is 0 } // Calculated the combined weight for an account function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { // Get the old combined weight old_combined_weight = _combined_weights[account]; // Get the veFXS multipliers // For the calculations, use the midpoint (analogous to midpoint Riemann sum) new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { // This is only called for the first stake to make sure the veFXS multiplier is not cut in half midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); } // Loop through the locked stakes, first by getting the liquidity * lock_multiplier portion new_combined_weight = 0; for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; // If the lock is expired if (thisStake.ending_timestamp <= block.timestamp) { // If the lock expired in the time since the last claim, the weight needs to be proportionately averaged this time if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = (thisStake.ending_timestamp).sub(lastRewardClaimTime[account]); uint256 time_after_expiry = (block.timestamp).sub(thisStake.ending_timestamp); // Get the weighted-average lock_multiplier uint256 numerator = ((lock_multiplier).mul(time_before_expiry)).add(((MULTIPLIER_PRECISION).mul(time_after_expiry))); lock_multiplier = numerator.div(time_before_expiry.add(time_after_expiry)); } // Otherwise, it needs to just be 1x else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(midpoint_vefxs_multiplier)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } // All the locked stakes for a given account function lockedStakesOf(address account) external view returns (LockedStake[] memory) { return lockedStakes[account]; } // All the locked stakes for a given account function getRewardSymbols() external view returns (string[] memory) { return rewardSymbols; } // All the reward tokens function getAllRewardTokens() external view returns (address[] memory) { return rewardTokens; } // Multiplier amount, given the length of the lock function lockMultiplier(uint256 secs) public view returns (uint256) { uint256 lock_multiplier = uint256(MULTIPLIER_PRECISION).add( secs .mul(lock_max_multiplier.sub(MULTIPLIER_PRECISION)) .div(lock_time_for_max_multiplier) ); if (lock_multiplier > lock_max_multiplier) lock_multiplier = lock_max_multiplier; return lock_multiplier; } // Last time the reward was applicable function lastTimeRewardApplicable() internal view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardRates(uint256 token_idx) public view returns (uint256 rwd_rate) { address gauge_controller_address = gaugeControllers[token_idx]; if (gauge_controller_address != address(0)) { rwd_rate = (IFraxGaugeController(gauge_controller_address).global_emission_rate()).mul(last_gauge_relative_weights[token_idx]).div(1e18); } else { rwd_rate = rewardRatesManual[token_idx]; } } // Amount of reward tokens per LP token function rewardsPerToken() public view returns (uint256[] memory newRewardsPerTokenStored) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return rewardsPerTokenStored; } else { newRewardsPerTokenStored = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ newRewardsPerTokenStored[i] = rewardsPerTokenStored[i].add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRates(i)).mul(1e18).div(_total_combined_weight) ); } return newRewardsPerTokenStored; } } // Amount of reward tokens an account has earned / accrued // Note: In the edge-case of one of the account's stake expiring since the last claim, this will // return a slightly inflated number function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] == 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = 0; } } else { for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = (_combined_weights[account]) .mul(reward_arr[i].sub(userRewardsPerTokenPaid[account][i])) .div(1e18) .add(rewards[account][i]); } } } // Total reward tokens emitted in the given period function getRewardForDuration() external view returns (uint256[] memory rewards_per_duration_arr) { rewards_per_duration_arr = new uint256[](rewardRatesManual.length); for (uint256 i = 0; i < rewardRatesManual.length; i++){ rewards_per_duration_arr[i] = rewardRates(i).mul(rewardsDuration); } } // See if the caller_addr is a manager for the reward token function isTokenManagerFor(address caller_addr, address reward_token_addr) public view returns (bool){ if (caller_addr == owner) return true; // Contract owner else if (rewardManagers[reward_token_addr] == caller_addr) return true; // Reward manager return false; } /* ========== MUTATIVE FUNCTIONS ========== */ // Staker can allow a migrator function stakerAllowMigrator(address migrator_address) external { require(valid_migrators[migrator_address], "Invalid migrator address"); staker_allowed_migrators[msg.sender][migrator_address] = true; } // Staker can disallow a previously-allowed migrator function stakerDisallowMigrator(address migrator_address) external { // Delete from the mapping delete staker_allowed_migrators[msg.sender][migrator_address]; } function _updateRewardAndBalance(address account, bool sync_too) internal { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one if (sync_too){ sync(); } if (account != address(0)) { // To keep the math correct, the user's combined weight must be recomputed to account for their // ever-changing veFXS balance. ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); // Calculate the earnings first _syncEarned(account); // Update the user's stored veFXS multipliers _vefxsMultiplierStored[account] = new_vefxs_multiplier; // Update the user's and the global combined weights if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight.sub(old_combined_weight); _total_combined_weight = _total_combined_weight.add(weight_diff); _combined_weights[account] = old_combined_weight.add(weight_diff); } else { uint256 weight_diff = old_combined_weight.sub(new_combined_weight); _total_combined_weight = _total_combined_weight.sub(weight_diff); _combined_weights[account] = old_combined_weight.sub(weight_diff); } } } function _syncEarned(address account) internal { if (account != address(0)) { // Calculate the earnings uint256[] memory earned_arr = earned(account); // Update the rewards array for (uint256 i = 0; i < earned_arr.length; i++){ rewards[account][i] = earned_arr[i]; } // Update the rewards paid array for (uint256 i = 0; i < earned_arr.length; i++){ userRewardsPerTokenPaid[account][i] = rewardsPerTokenStored[i]; } } } // Two different stake functions are needed because of delegateCall and msg.sender issues function stakeLocked(uint256 liquidity, uint256 secs) nonReentrant public { _stakeLocked(msg.sender, msg.sender, liquidity, secs, block.timestamp); } // If this were not internal, and source_address had an infinite approve, this could be exploitable // (pull funds from source_address and stake for an arbitrary staker_address) function _stakeLocked( address staker_address, address source_address, uint256 liquidity, uint256 secs, uint256 start_timestamp ) internal updateRewardAndBalance(staker_address, true) { require(!stakingPaused, "Staking paused"); require(liquidity > 0, "Must stake more than zero"); require(greylist[staker_address] == false, "Address has been greylisted"); require(secs >= lock_time_min, "Minimum stake time not met"); require(secs <= lock_time_for_max_multiplier,"Trying to lock for too long"); uint256 lock_multiplier = lockMultiplier(secs); bytes32 kek_id = keccak256(abi.encodePacked(staker_address, start_timestamp, liquidity, _locked_liquidity[staker_address])); lockedStakes[staker_address].push(LockedStake( kek_id, start_timestamp, liquidity, start_timestamp.add(secs), lock_multiplier )); // Pull the tokens from the source_address TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity); // Update liquidities _total_liquidity_locked = _total_liquidity_locked.add(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].add(liquidity); // Need to call to update the combined weights _updateRewardAndBalance(staker_address, false); // Needed for edge case if the staker only claims once, and after the lock expired if (lastRewardClaimTime[staker_address] == 0) lastRewardClaimTime[staker_address] = block.timestamp; emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address); } // Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues function withdrawLocked(bytes32 kek_id) nonReentrant public { require(withdrawalsPaused == false, "Withdrawals paused"); _withdrawLocked(msg.sender, msg.sender, kek_id); } // No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper // functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked() function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal { // Collect rewards first and then update the balances _getReward(staker_address, destination_address); LockedStake memory thisStake; thisStake.liquidity = 0; uint theArrayIndex; for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ thisStake = lockedStakes[staker_address][i]; theArrayIndex = i; break; } } require(thisStake.kek_id == kek_id, "Stake not found"); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { // Update liquidities _total_liquidity_locked = _total_liquidity_locked.sub(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].sub(liquidity); // Remove the stake from the array delete lockedStakes[staker_address][theArrayIndex]; // Need to call to update the combined weights _updateRewardAndBalance(staker_address, false); // Give the tokens to the destination_address // Should throw if insufficient balance stakingToken.transfer(destination_address, liquidity); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } // Two different getReward functions are needed because of delegateCall and msg.sender issues function getReward() external nonReentrant returns (uint256[] memory) { require(rewardsCollectionPaused == false,"Rewards collection paused"); return _getReward(msg.sender, msg.sender); } // No withdrawer == msg.sender check needed since this is only internally callable function _getReward(address rewardee, address destination_address) internal updateRewardAndBalance(rewardee, true) returns (uint256[] memory rewards_before) { // Update the rewards array and distribute rewards rewards_before = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardTokens.length; i++){ rewards_before[i] = rewards[rewardee][i]; rewards[rewardee][i] = 0; ERC20(rewardTokens[i]).transfer(destination_address, rewards_before[i]); emit RewardPaid(rewardee, rewards_before[i], rewardTokens[i], destination_address); } lastRewardClaimTime[rewardee] = block.timestamp; } // If the period expired, renew it function retroCatchUp() internal { // Pull in rewards from the rewards distributor rewards_distributor.distributeReward(address(this)); // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period // Make sure there are enough tokens to renew the reward period for (uint256 i = 0; i < rewardTokens.length; i++){ require(rewardRates(i).mul(rewardsDuration).mul(num_periods_elapsed + 1) <= ERC20(rewardTokens[i]).balanceOf(address(this)), string(abi.encodePacked("Not enough reward tokens available: ", rewardTokens[i])) ); } // uint256 old_lastUpdateTime = lastUpdateTime; // uint256 new_lastUpdateTime = block.timestamp; // lastUpdateTime = periodFinish; periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration)); _updateStoredRewardsAndTime(); emit RewardsPeriodRenewed(address(stakingToken)); } function _updateStoredRewardsAndTime() internal { // Get the rewards uint256[] memory rewards_per_token = rewardsPerToken(); // Update the rewardsPerTokenStored for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ rewardsPerTokenStored[i] = rewards_per_token[i]; } // Update the last stored time lastUpdateTime = lastTimeRewardApplicable(); } function sync_gauge_weights(bool force_update) public { // Loop through the gauge controllers for (uint256 i = 0; i < gaugeControllers.length; i++){ address gauge_controller_address = gaugeControllers[i]; if (gauge_controller_address != address(0)) { if (force_update || (block.timestamp > last_gauge_time_totals[i])){ // Update the gauge_relative_weight last_gauge_relative_weights[i] = IFraxGaugeController(gauge_controller_address).gauge_relative_weight_write(address(this), block.timestamp); last_gauge_time_totals[i] = IFraxGaugeController(gauge_controller_address).time_total(); } } } } function sync() public { // Sync the gauge weight, if applicable sync_gauge_weights(false); if (block.timestamp >= periodFinish) { retroCatchUp(); } else { _updateStoredRewardsAndTime(); } } /* ========== RESTRICTED FUNCTIONS ========== */ // Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can). function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs, uint256 start_timestamp) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _stakeLocked(staker_address, msg.sender, amount, secs, start_timestamp); } // Used for migrations function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _withdrawLocked(staker_address, msg.sender, kek_id); } // Adds supported migrator address function addMigrator(address migrator_address) external onlyByOwner { valid_migrators[migrator_address] = true; } // Remove a migrator address function removeMigrator(address migrator_address) external onlyByOwner { require(valid_migrators[migrator_address] == true, "Address nonexistant"); // Delete from the mapping delete valid_migrators[migrator_address]; } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { // Check if the desired token is a reward token bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } // Only the reward managers can take back their reward tokens if (isRewardToken && rewardManagers[tokenAddress] == msg.sender){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } // Other tokens, like the staking token, airdrops, or accidental deposits, can be withdrawn by the owner else if (!isRewardToken && (msg.sender == owner)){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } // If none of the above conditions are true else { revert("No valid tokens to recover"); } } function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwner { require(_rewardsDuration >= 86400, "Rewards duration too short"); require( periodFinish == 0 || block.timestamp > periodFinish, "Reward period incomplete" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } function setMultipliers(uint256 _lock_max_multiplier, uint256 _vefxs_max_multiplier, uint256 _vefxs_per_frax_for_max_boost) external onlyByOwner { require(_lock_max_multiplier >= MULTIPLIER_PRECISION, "Mult must be >= MULTIPLIER_PRECISION"); require(_vefxs_max_multiplier >= 0, "veFXS mul must be >= 0"); require(_vefxs_per_frax_for_max_boost > 0, "veFXS pct max must be >= 0"); lock_max_multiplier = _lock_max_multiplier; vefxs_max_multiplier = _vefxs_max_multiplier; vefxs_per_frax_for_max_boost = _vefxs_per_frax_for_max_boost; emit MaxVeFXSMultiplier(vefxs_max_multiplier); emit LockedStakeMaxMultiplierUpdated(lock_max_multiplier); emit veFXSPerFraxForMaxBoostUpdated(vefxs_per_frax_for_max_boost); } function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _lock_time_for_max_multiplier, uint256 _lock_time_min) external onlyByOwner { require(_lock_time_for_max_multiplier >= 1, "Mul max time must be >= 1"); require(_lock_time_min >= 1, "Mul min time must be >= 1"); lock_time_for_max_multiplier = _lock_time_for_max_multiplier; lock_time_min = _lock_time_min; emit LockedStakeTimeForMaxMultiplier(lock_time_for_max_multiplier); emit LockedStakeMinTime(_lock_time_min); } function greylistAddress(address _address) external onlyByOwner { greylist[_address] = !(greylist[_address]); } function unlockStakes() external onlyByOwner { stakesUnlocked = !stakesUnlocked; } function toggleStaking() external onlyByOwner { stakingPaused = !stakingPaused; } function toggleMigrations() external onlyByOwner { migrationsOn = !migrationsOn; } function toggleWithdrawals() external onlyByOwner { withdrawalsPaused = !withdrawalsPaused; } function toggleRewardsCollection() external onlyByOwner { rewardsCollectionPaused = !rewardsCollectionPaused; } // The owner or the reward token managers can set reward rates function setRewardRate(address reward_token_address, uint256 new_rate, bool sync_too) external onlyTknMgrs(reward_token_address) { rewardRatesManual[rewardTokenAddrToIdx[reward_token_address]] = new_rate; if (sync_too){ sync(); } } // The owner or the reward token managers can set reward rates function setGaugeController(address reward_token_address, address _rewards_distributor_address, address _gauge_controller_address, bool sync_too) external onlyTknMgrs(reward_token_address) { gaugeControllers[rewardTokenAddrToIdx[reward_token_address]] = _gauge_controller_address; rewards_distributor = IFraxGaugeFXSRewardsDistributor(_rewards_distributor_address); if (sync_too){ sync(); } } // The owner or the reward token managers can change managers function changeTokenManager(address reward_token_address, address new_manager_address) external onlyTknMgrs(reward_token_address) { rewardManagers[reward_token_address] = new_manager_address; } /* ========== EVENTS ========== */ event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address); event WithdrawLocked(address indexed user, uint256 amount, bytes32 kek_id, address destination_address); event RewardPaid(address indexed user, uint256 reward, address token_address, address destination_address); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address destination_address, address token, uint256 amount); event RewardsPeriodRenewed(address token); event LockedStakeMaxMultiplierUpdated(uint256 multiplier); event LockedStakeTimeForMaxMultiplier(uint256 secs); event LockedStakeMinTime(uint256 secs); event MaxVeFXSMultiplier(uint256 multiplier); event veFXSPerFraxForMaxBoostUpdated(uint256 scale_factor); } // File contracts/Staking/Variants/StakingRewardsMultiGauge_StakeDAO_FRAX_Put.sol contract StakingRewardsMultiGauge_StakeDAO_FRAX_Put is StakingRewardsMultiGauge { constructor ( address _owner, address _stakingToken, address _rewards_distributor_address, string[] memory _rewardSymbols, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRates, address[] memory _gaugeControllers ) StakingRewardsMultiGauge(_owner, _stakingToken, _rewards_distributor_address, _rewardSymbols, _rewardTokens, _rewardManagers, _rewardRates, _gaugeControllers) {} }
Instances -------------------- VARIES -------------------- G-UNI IGUniPool public stakingToken; mStable IFeederPool public stakingToken; sdETH-FraxPut Vault StakeDAO Vault IStakeDaoVault public stakingToken; Uniswap V2 IUniswapV2Pair public stakingToken; ------------------------------------------------ FRAX Constant for various precisions Time tracking Lock time and multiplier settings veFXS related Reward addresses, gauge addresses, reward rates, and reward managers Reward period Reward tracking Balance tracking List of valid migrators (set by governance) Stakers set which migrator(s) they want to use Uniswap V2 (or G-UNI) ONLY Stake tracking Greylisting of bad addresses Administrative booleans
contract StakingRewardsMultiGauge is Owned, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; IveFXS private veFXS = IveFXS(0xc8418aF6358FFddA74e09Ca9CC3Fe03Ca6aDC5b0); IOpynPerpVault public stakingToken; IFraxGaugeFXSRewardsDistributor public rewards_distributor; address private constant frax_address = 0x853d955aCEf822Db058eb8505911ED77F175b99e; uint256 private constant MULTIPLIER_PRECISION = 1e18; uint256 public periodFinish; uint256 public lastUpdateTime; mapping(address => uint256) private _vefxsMultiplierStored; address[] public rewardTokens; address[] public gaugeControllers; uint256[] public rewardRatesManual; string[] public rewardSymbols; uint256[] private rewardsPerTokenStored; uint256[] private last_gauge_relative_weights; uint256[] private last_gauge_time_totals; uint256 private _total_liquidity_locked; uint256 private _total_combined_weight; mapping(address => uint256) private _locked_liquidity; mapping(address => uint256) private _combined_weights; mapping(address => bool) public valid_migrators; mapping(address => mapping(address => bool)) public staker_allowed_migrators; bool frax_is_token0; mapping(address => LockedStake[]) private lockedStakes; mapping(address => bool) public greylist; struct LockedStake { bytes32 kek_id; uint256 start_timestamp; uint256 liquidity; uint256 ending_timestamp; } modifier onlyByOwner() { require(msg.sender == owner, "Not the owner"); _; } modifier onlyTknMgrs(address reward_token_address) { require(msg.sender == owner || isTokenManagerFor(msg.sender, reward_token_address), "Not owner or tkn mgr"); _; } modifier isMigrating() { require(migrationsOn == true, "Not in migration"); _; } modifier notStakingPaused() { require(stakingPaused == false, "Staking paused"); _; } modifier updateRewardAndBalance(address account, bool sync_too) { _updateRewardAndBalance(account, sync_too); _; } constructor ( address _owner, address _stakingToken, address _rewards_distributor_address, string[] memory _rewardSymbols, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRatesManual, address[] memory _gaugeControllers ) Owned(_owner){ stakingToken = IOpynPerpVault(_stakingToken); rewards_distributor = IFraxGaugeFXSRewardsDistributor(_rewards_distributor_address); rewardTokens = _rewardTokens; gaugeControllers = _gaugeControllers; rewardRatesManual = _rewardRatesManual; rewardSymbols = _rewardSymbols; for (uint256 i = 0; i < _rewardTokens.length; i++){ rewardTokenAddrToIdx[_rewardTokens[i]] = i; rewardsPerTokenStored.push(0); rewardManagers[_rewardTokens[i]] = _rewardManagers[i]; last_gauge_relative_weights.push(0); last_gauge_time_totals.push(0); } periodFinish = block.timestamp.add(rewardsDuration); } ) Owned(_owner){ stakingToken = IOpynPerpVault(_stakingToken); rewards_distributor = IFraxGaugeFXSRewardsDistributor(_rewards_distributor_address); rewardTokens = _rewardTokens; gaugeControllers = _gaugeControllers; rewardRatesManual = _rewardRatesManual; rewardSymbols = _rewardSymbols; for (uint256 i = 0; i < _rewardTokens.length; i++){ rewardTokenAddrToIdx[_rewardTokens[i]] = i; rewardsPerTokenStored.push(0); rewardManagers[_rewardTokens[i]] = _rewardManagers[i]; last_gauge_relative_weights.push(0); last_gauge_time_totals.push(0); } periodFinish = block.timestamp.add(rewardsDuration); } stakesUnlocked = false; lastUpdateTime = block.timestamp; function totalLiquidityLocked() external view returns (uint256) { return _total_liquidity_locked; } function lockedLiquidityOf(address account) external view returns (uint256) { return _locked_liquidity[account]; } function totalCombinedWeight() external view returns (uint256) { return _total_combined_weight; } function combinedWeightOf(address account) external view returns (uint256) { return _combined_weights[account]; } function fraxPerLPToken() public view returns (uint256) { uint256 frax_per_lp_token; { uint256 frax3crv_held = stakingToken.totalUnderlyingControlled(); frax_per_lp_token = (frax3crv_held.mul(1e18).div(stakingToken.totalSupply())) / 2; } return frax_per_lp_token; } function fraxPerLPToken() public view returns (uint256) { uint256 frax_per_lp_token; { uint256 frax3crv_held = stakingToken.totalUnderlyingControlled(); frax_per_lp_token = (frax3crv_held.mul(1e18).div(stakingToken.totalSupply())) / 2; } return frax_per_lp_token; } function userStakedFrax(address account) public view returns (uint256) { return (fraxPerLPToken()).mul(_locked_liquidity[account]).div(1e18); } function minVeFXSForMaxBoost(address account) public view returns (uint256) { return (userStakedFrax(account)).mul(vefxs_per_frax_for_max_boost).div(MULTIPLIER_PRECISION); } function veFXSMultiplier(address account) public view returns (uint256) { uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (veFXS.balanceOf(account)).mul(MULTIPLIER_PRECISION).div(veFXS_needed_for_max_boost); uint256 vefxs_multiplier = ((user_vefxs_fraction).mul(vefxs_max_multiplier)).div(MULTIPLIER_PRECISION); if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier; return vefxs_multiplier; } } function veFXSMultiplier(address account) public view returns (uint256) { uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (veFXS.balanceOf(account)).mul(MULTIPLIER_PRECISION).div(veFXS_needed_for_max_boost); uint256 vefxs_multiplier = ((user_vefxs_fraction).mul(vefxs_max_multiplier)).div(MULTIPLIER_PRECISION); if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier; return vefxs_multiplier; } } function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { old_combined_weight = _combined_weights[account]; new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); } for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; if (thisStake.ending_timestamp <= block.timestamp) { if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = (thisStake.ending_timestamp).sub(lastRewardClaimTime[account]); uint256 time_after_expiry = (block.timestamp).sub(thisStake.ending_timestamp); uint256 numerator = ((lock_multiplier).mul(time_before_expiry)).add(((MULTIPLIER_PRECISION).mul(time_after_expiry))); lock_multiplier = numerator.div(time_before_expiry.add(time_after_expiry)); } else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(midpoint_vefxs_multiplier)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { old_combined_weight = _combined_weights[account]; new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); } for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; if (thisStake.ending_timestamp <= block.timestamp) { if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = (thisStake.ending_timestamp).sub(lastRewardClaimTime[account]); uint256 time_after_expiry = (block.timestamp).sub(thisStake.ending_timestamp); uint256 numerator = ((lock_multiplier).mul(time_before_expiry)).add(((MULTIPLIER_PRECISION).mul(time_after_expiry))); lock_multiplier = numerator.div(time_before_expiry.add(time_after_expiry)); } else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(midpoint_vefxs_multiplier)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { old_combined_weight = _combined_weights[account]; new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); } for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; if (thisStake.ending_timestamp <= block.timestamp) { if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = (thisStake.ending_timestamp).sub(lastRewardClaimTime[account]); uint256 time_after_expiry = (block.timestamp).sub(thisStake.ending_timestamp); uint256 numerator = ((lock_multiplier).mul(time_before_expiry)).add(((MULTIPLIER_PRECISION).mul(time_after_expiry))); lock_multiplier = numerator.div(time_before_expiry.add(time_after_expiry)); } else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(midpoint_vefxs_multiplier)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } new_combined_weight = 0; function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { old_combined_weight = _combined_weights[account]; new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); } for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; if (thisStake.ending_timestamp <= block.timestamp) { if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = (thisStake.ending_timestamp).sub(lastRewardClaimTime[account]); uint256 time_after_expiry = (block.timestamp).sub(thisStake.ending_timestamp); uint256 numerator = ((lock_multiplier).mul(time_before_expiry)).add(((MULTIPLIER_PRECISION).mul(time_after_expiry))); lock_multiplier = numerator.div(time_before_expiry.add(time_after_expiry)); } else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(midpoint_vefxs_multiplier)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { old_combined_weight = _combined_weights[account]; new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); } for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; if (thisStake.ending_timestamp <= block.timestamp) { if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = (thisStake.ending_timestamp).sub(lastRewardClaimTime[account]); uint256 time_after_expiry = (block.timestamp).sub(thisStake.ending_timestamp); uint256 numerator = ((lock_multiplier).mul(time_before_expiry)).add(((MULTIPLIER_PRECISION).mul(time_after_expiry))); lock_multiplier = numerator.div(time_before_expiry.add(time_after_expiry)); } else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(midpoint_vefxs_multiplier)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { old_combined_weight = _combined_weights[account]; new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); } for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; if (thisStake.ending_timestamp <= block.timestamp) { if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = (thisStake.ending_timestamp).sub(lastRewardClaimTime[account]); uint256 time_after_expiry = (block.timestamp).sub(thisStake.ending_timestamp); uint256 numerator = ((lock_multiplier).mul(time_before_expiry)).add(((MULTIPLIER_PRECISION).mul(time_after_expiry))); lock_multiplier = numerator.div(time_before_expiry.add(time_after_expiry)); } else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(midpoint_vefxs_multiplier)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { old_combined_weight = _combined_weights[account]; new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); } for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; if (thisStake.ending_timestamp <= block.timestamp) { if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = (thisStake.ending_timestamp).sub(lastRewardClaimTime[account]); uint256 time_after_expiry = (block.timestamp).sub(thisStake.ending_timestamp); uint256 numerator = ((lock_multiplier).mul(time_before_expiry)).add(((MULTIPLIER_PRECISION).mul(time_after_expiry))); lock_multiplier = numerator.div(time_before_expiry.add(time_after_expiry)); } else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(midpoint_vefxs_multiplier)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } function lockedStakesOf(address account) external view returns (LockedStake[] memory) { return lockedStakes[account]; } function getRewardSymbols() external view returns (string[] memory) { return rewardSymbols; } function getAllRewardTokens() external view returns (address[] memory) { return rewardTokens; } function lockMultiplier(uint256 secs) public view returns (uint256) { uint256 lock_multiplier = uint256(MULTIPLIER_PRECISION).add( secs .mul(lock_max_multiplier.sub(MULTIPLIER_PRECISION)) .div(lock_time_for_max_multiplier) ); if (lock_multiplier > lock_max_multiplier) lock_multiplier = lock_max_multiplier; return lock_multiplier; } function lastTimeRewardApplicable() internal view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardRates(uint256 token_idx) public view returns (uint256 rwd_rate) { address gauge_controller_address = gaugeControllers[token_idx]; if (gauge_controller_address != address(0)) { rwd_rate = (IFraxGaugeController(gauge_controller_address).global_emission_rate()).mul(last_gauge_relative_weights[token_idx]).div(1e18); } else { rwd_rate = rewardRatesManual[token_idx]; } } function rewardRates(uint256 token_idx) public view returns (uint256 rwd_rate) { address gauge_controller_address = gaugeControllers[token_idx]; if (gauge_controller_address != address(0)) { rwd_rate = (IFraxGaugeController(gauge_controller_address).global_emission_rate()).mul(last_gauge_relative_weights[token_idx]).div(1e18); } else { rwd_rate = rewardRatesManual[token_idx]; } } function rewardRates(uint256 token_idx) public view returns (uint256 rwd_rate) { address gauge_controller_address = gaugeControllers[token_idx]; if (gauge_controller_address != address(0)) { rwd_rate = (IFraxGaugeController(gauge_controller_address).global_emission_rate()).mul(last_gauge_relative_weights[token_idx]).div(1e18); } else { rwd_rate = rewardRatesManual[token_idx]; } } function rewardsPerToken() public view returns (uint256[] memory newRewardsPerTokenStored) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return rewardsPerTokenStored; } else { newRewardsPerTokenStored = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ newRewardsPerTokenStored[i] = rewardsPerTokenStored[i].add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRates(i)).mul(1e18).div(_total_combined_weight) ); } return newRewardsPerTokenStored; } } function rewardsPerToken() public view returns (uint256[] memory newRewardsPerTokenStored) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return rewardsPerTokenStored; } else { newRewardsPerTokenStored = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ newRewardsPerTokenStored[i] = rewardsPerTokenStored[i].add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRates(i)).mul(1e18).div(_total_combined_weight) ); } return newRewardsPerTokenStored; } } function rewardsPerToken() public view returns (uint256[] memory newRewardsPerTokenStored) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return rewardsPerTokenStored; } else { newRewardsPerTokenStored = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ newRewardsPerTokenStored[i] = rewardsPerTokenStored[i].add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRates(i)).mul(1e18).div(_total_combined_weight) ); } return newRewardsPerTokenStored; } } function rewardsPerToken() public view returns (uint256[] memory newRewardsPerTokenStored) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return rewardsPerTokenStored; } else { newRewardsPerTokenStored = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ newRewardsPerTokenStored[i] = rewardsPerTokenStored[i].add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRates(i)).mul(1e18).div(_total_combined_weight) ); } return newRewardsPerTokenStored; } } function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] == 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = 0; } } else { for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = (_combined_weights[account]) .mul(reward_arr[i].sub(userRewardsPerTokenPaid[account][i])) .div(1e18) .add(rewards[account][i]); } } } function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] == 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = 0; } } else { for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = (_combined_weights[account]) .mul(reward_arr[i].sub(userRewardsPerTokenPaid[account][i])) .div(1e18) .add(rewards[account][i]); } } } function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] == 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = 0; } } else { for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = (_combined_weights[account]) .mul(reward_arr[i].sub(userRewardsPerTokenPaid[account][i])) .div(1e18) .add(rewards[account][i]); } } } function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] == 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = 0; } } else { for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = (_combined_weights[account]) .mul(reward_arr[i].sub(userRewardsPerTokenPaid[account][i])) .div(1e18) .add(rewards[account][i]); } } } function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] == 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = 0; } } else { for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = (_combined_weights[account]) .mul(reward_arr[i].sub(userRewardsPerTokenPaid[account][i])) .div(1e18) .add(rewards[account][i]); } } } function getRewardForDuration() external view returns (uint256[] memory rewards_per_duration_arr) { rewards_per_duration_arr = new uint256[](rewardRatesManual.length); for (uint256 i = 0; i < rewardRatesManual.length; i++){ rewards_per_duration_arr[i] = rewardRates(i).mul(rewardsDuration); } } function getRewardForDuration() external view returns (uint256[] memory rewards_per_duration_arr) { rewards_per_duration_arr = new uint256[](rewardRatesManual.length); for (uint256 i = 0; i < rewardRatesManual.length; i++){ rewards_per_duration_arr[i] = rewardRates(i).mul(rewardsDuration); } } function isTokenManagerFor(address caller_addr, address reward_token_addr) public view returns (bool){ return false; } function stakerAllowMigrator(address migrator_address) external { require(valid_migrators[migrator_address], "Invalid migrator address"); staker_allowed_migrators[msg.sender][migrator_address] = true; } function stakerDisallowMigrator(address migrator_address) external { delete staker_allowed_migrators[msg.sender][migrator_address]; } function _updateRewardAndBalance(address account, bool sync_too) internal { if (sync_too){ sync(); } if (account != address(0)) { ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); _syncEarned(account); _vefxsMultiplierStored[account] = new_vefxs_multiplier; if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight.sub(old_combined_weight); _total_combined_weight = _total_combined_weight.add(weight_diff); _combined_weights[account] = old_combined_weight.add(weight_diff); uint256 weight_diff = old_combined_weight.sub(new_combined_weight); _total_combined_weight = _total_combined_weight.sub(weight_diff); _combined_weights[account] = old_combined_weight.sub(weight_diff); } } } function _updateRewardAndBalance(address account, bool sync_too) internal { if (sync_too){ sync(); } if (account != address(0)) { ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); _syncEarned(account); _vefxsMultiplierStored[account] = new_vefxs_multiplier; if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight.sub(old_combined_weight); _total_combined_weight = _total_combined_weight.add(weight_diff); _combined_weights[account] = old_combined_weight.add(weight_diff); uint256 weight_diff = old_combined_weight.sub(new_combined_weight); _total_combined_weight = _total_combined_weight.sub(weight_diff); _combined_weights[account] = old_combined_weight.sub(weight_diff); } } } function _updateRewardAndBalance(address account, bool sync_too) internal { if (sync_too){ sync(); } if (account != address(0)) { ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); _syncEarned(account); _vefxsMultiplierStored[account] = new_vefxs_multiplier; if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight.sub(old_combined_weight); _total_combined_weight = _total_combined_weight.add(weight_diff); _combined_weights[account] = old_combined_weight.add(weight_diff); uint256 weight_diff = old_combined_weight.sub(new_combined_weight); _total_combined_weight = _total_combined_weight.sub(weight_diff); _combined_weights[account] = old_combined_weight.sub(weight_diff); } } } function _updateRewardAndBalance(address account, bool sync_too) internal { if (sync_too){ sync(); } if (account != address(0)) { ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); _syncEarned(account); _vefxsMultiplierStored[account] = new_vefxs_multiplier; if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight.sub(old_combined_weight); _total_combined_weight = _total_combined_weight.add(weight_diff); _combined_weights[account] = old_combined_weight.add(weight_diff); uint256 weight_diff = old_combined_weight.sub(new_combined_weight); _total_combined_weight = _total_combined_weight.sub(weight_diff); _combined_weights[account] = old_combined_weight.sub(weight_diff); } } } } else { function _syncEarned(address account) internal { if (account != address(0)) { uint256[] memory earned_arr = earned(account); for (uint256 i = 0; i < earned_arr.length; i++){ rewards[account][i] = earned_arr[i]; } for (uint256 i = 0; i < earned_arr.length; i++){ userRewardsPerTokenPaid[account][i] = rewardsPerTokenStored[i]; } } } function _syncEarned(address account) internal { if (account != address(0)) { uint256[] memory earned_arr = earned(account); for (uint256 i = 0; i < earned_arr.length; i++){ rewards[account][i] = earned_arr[i]; } for (uint256 i = 0; i < earned_arr.length; i++){ userRewardsPerTokenPaid[account][i] = rewardsPerTokenStored[i]; } } } function _syncEarned(address account) internal { if (account != address(0)) { uint256[] memory earned_arr = earned(account); for (uint256 i = 0; i < earned_arr.length; i++){ rewards[account][i] = earned_arr[i]; } for (uint256 i = 0; i < earned_arr.length; i++){ userRewardsPerTokenPaid[account][i] = rewardsPerTokenStored[i]; } } } function _syncEarned(address account) internal { if (account != address(0)) { uint256[] memory earned_arr = earned(account); for (uint256 i = 0; i < earned_arr.length; i++){ rewards[account][i] = earned_arr[i]; } for (uint256 i = 0; i < earned_arr.length; i++){ userRewardsPerTokenPaid[account][i] = rewardsPerTokenStored[i]; } } } function stakeLocked(uint256 liquidity, uint256 secs) nonReentrant public { _stakeLocked(msg.sender, msg.sender, liquidity, secs, block.timestamp); } function _stakeLocked( address staker_address, address source_address, uint256 liquidity, uint256 secs, uint256 start_timestamp ) internal updateRewardAndBalance(staker_address, true) { require(!stakingPaused, "Staking paused"); require(liquidity > 0, "Must stake more than zero"); require(greylist[staker_address] == false, "Address has been greylisted"); require(secs >= lock_time_min, "Minimum stake time not met"); require(secs <= lock_time_for_max_multiplier,"Trying to lock for too long"); uint256 lock_multiplier = lockMultiplier(secs); bytes32 kek_id = keccak256(abi.encodePacked(staker_address, start_timestamp, liquidity, _locked_liquidity[staker_address])); lockedStakes[staker_address].push(LockedStake( kek_id, start_timestamp, liquidity, start_timestamp.add(secs), lock_multiplier )); TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity); _total_liquidity_locked = _total_liquidity_locked.add(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].add(liquidity); _updateRewardAndBalance(staker_address, false); if (lastRewardClaimTime[staker_address] == 0) lastRewardClaimTime[staker_address] = block.timestamp; emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address); } function withdrawLocked(bytes32 kek_id) nonReentrant public { require(withdrawalsPaused == false, "Withdrawals paused"); _withdrawLocked(msg.sender, msg.sender, kek_id); } function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal { _getReward(staker_address, destination_address); LockedStake memory thisStake; thisStake.liquidity = 0; uint theArrayIndex; for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ thisStake = lockedStakes[staker_address][i]; theArrayIndex = i; break; } } require(thisStake.kek_id == kek_id, "Stake not found"); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { _total_liquidity_locked = _total_liquidity_locked.sub(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].sub(liquidity); delete lockedStakes[staker_address][theArrayIndex]; _updateRewardAndBalance(staker_address, false); stakingToken.transfer(destination_address, liquidity); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal { _getReward(staker_address, destination_address); LockedStake memory thisStake; thisStake.liquidity = 0; uint theArrayIndex; for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ thisStake = lockedStakes[staker_address][i]; theArrayIndex = i; break; } } require(thisStake.kek_id == kek_id, "Stake not found"); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { _total_liquidity_locked = _total_liquidity_locked.sub(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].sub(liquidity); delete lockedStakes[staker_address][theArrayIndex]; _updateRewardAndBalance(staker_address, false); stakingToken.transfer(destination_address, liquidity); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal { _getReward(staker_address, destination_address); LockedStake memory thisStake; thisStake.liquidity = 0; uint theArrayIndex; for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ thisStake = lockedStakes[staker_address][i]; theArrayIndex = i; break; } } require(thisStake.kek_id == kek_id, "Stake not found"); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { _total_liquidity_locked = _total_liquidity_locked.sub(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].sub(liquidity); delete lockedStakes[staker_address][theArrayIndex]; _updateRewardAndBalance(staker_address, false); stakingToken.transfer(destination_address, liquidity); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal { _getReward(staker_address, destination_address); LockedStake memory thisStake; thisStake.liquidity = 0; uint theArrayIndex; for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ thisStake = lockedStakes[staker_address][i]; theArrayIndex = i; break; } } require(thisStake.kek_id == kek_id, "Stake not found"); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { _total_liquidity_locked = _total_liquidity_locked.sub(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].sub(liquidity); delete lockedStakes[staker_address][theArrayIndex]; _updateRewardAndBalance(staker_address, false); stakingToken.transfer(destination_address, liquidity); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } function getReward() external nonReentrant returns (uint256[] memory) { require(rewardsCollectionPaused == false,"Rewards collection paused"); return _getReward(msg.sender, msg.sender); } function _getReward(address rewardee, address destination_address) internal updateRewardAndBalance(rewardee, true) returns (uint256[] memory rewards_before) { rewards_before = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardTokens.length; i++){ rewards_before[i] = rewards[rewardee][i]; rewards[rewardee][i] = 0; ERC20(rewardTokens[i]).transfer(destination_address, rewards_before[i]); emit RewardPaid(rewardee, rewards_before[i], rewardTokens[i], destination_address); } lastRewardClaimTime[rewardee] = block.timestamp; } function _getReward(address rewardee, address destination_address) internal updateRewardAndBalance(rewardee, true) returns (uint256[] memory rewards_before) { rewards_before = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardTokens.length; i++){ rewards_before[i] = rewards[rewardee][i]; rewards[rewardee][i] = 0; ERC20(rewardTokens[i]).transfer(destination_address, rewards_before[i]); emit RewardPaid(rewardee, rewards_before[i], rewardTokens[i], destination_address); } lastRewardClaimTime[rewardee] = block.timestamp; } function retroCatchUp() internal { rewards_distributor.distributeReward(address(this)); for (uint256 i = 0; i < rewardTokens.length; i++){ require(rewardRates(i).mul(rewardsDuration).mul(num_periods_elapsed + 1) <= ERC20(rewardTokens[i]).balanceOf(address(this)), string(abi.encodePacked("Not enough reward tokens available: ", rewardTokens[i])) ); } _updateStoredRewardsAndTime(); emit RewardsPeriodRenewed(address(stakingToken)); } function retroCatchUp() internal { rewards_distributor.distributeReward(address(this)); for (uint256 i = 0; i < rewardTokens.length; i++){ require(rewardRates(i).mul(rewardsDuration).mul(num_periods_elapsed + 1) <= ERC20(rewardTokens[i]).balanceOf(address(this)), string(abi.encodePacked("Not enough reward tokens available: ", rewardTokens[i])) ); } _updateStoredRewardsAndTime(); emit RewardsPeriodRenewed(address(stakingToken)); } periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration)); function _updateStoredRewardsAndTime() internal { uint256[] memory rewards_per_token = rewardsPerToken(); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ rewardsPerTokenStored[i] = rewards_per_token[i]; } } function _updateStoredRewardsAndTime() internal { uint256[] memory rewards_per_token = rewardsPerToken(); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ rewardsPerTokenStored[i] = rewards_per_token[i]; } } lastUpdateTime = lastTimeRewardApplicable(); function sync_gauge_weights(bool force_update) public { for (uint256 i = 0; i < gaugeControllers.length; i++){ address gauge_controller_address = gaugeControllers[i]; if (gauge_controller_address != address(0)) { if (force_update || (block.timestamp > last_gauge_time_totals[i])){ last_gauge_relative_weights[i] = IFraxGaugeController(gauge_controller_address).gauge_relative_weight_write(address(this), block.timestamp); last_gauge_time_totals[i] = IFraxGaugeController(gauge_controller_address).time_total(); } } } } function sync_gauge_weights(bool force_update) public { for (uint256 i = 0; i < gaugeControllers.length; i++){ address gauge_controller_address = gaugeControllers[i]; if (gauge_controller_address != address(0)) { if (force_update || (block.timestamp > last_gauge_time_totals[i])){ last_gauge_relative_weights[i] = IFraxGaugeController(gauge_controller_address).gauge_relative_weight_write(address(this), block.timestamp); last_gauge_time_totals[i] = IFraxGaugeController(gauge_controller_address).time_total(); } } } } function sync_gauge_weights(bool force_update) public { for (uint256 i = 0; i < gaugeControllers.length; i++){ address gauge_controller_address = gaugeControllers[i]; if (gauge_controller_address != address(0)) { if (force_update || (block.timestamp > last_gauge_time_totals[i])){ last_gauge_relative_weights[i] = IFraxGaugeController(gauge_controller_address).gauge_relative_weight_write(address(this), block.timestamp); last_gauge_time_totals[i] = IFraxGaugeController(gauge_controller_address).time_total(); } } } } function sync_gauge_weights(bool force_update) public { for (uint256 i = 0; i < gaugeControllers.length; i++){ address gauge_controller_address = gaugeControllers[i]; if (gauge_controller_address != address(0)) { if (force_update || (block.timestamp > last_gauge_time_totals[i])){ last_gauge_relative_weights[i] = IFraxGaugeController(gauge_controller_address).gauge_relative_weight_write(address(this), block.timestamp); last_gauge_time_totals[i] = IFraxGaugeController(gauge_controller_address).time_total(); } } } } function sync() public { sync_gauge_weights(false); if (block.timestamp >= periodFinish) { retroCatchUp(); } else { _updateStoredRewardsAndTime(); } } function sync() public { sync_gauge_weights(false); if (block.timestamp >= periodFinish) { retroCatchUp(); } else { _updateStoredRewardsAndTime(); } } function sync() public { sync_gauge_weights(false); if (block.timestamp >= periodFinish) { retroCatchUp(); } else { _updateStoredRewardsAndTime(); } } function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs, uint256 start_timestamp) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _stakeLocked(staker_address, msg.sender, amount, secs, start_timestamp); } function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _withdrawLocked(staker_address, msg.sender, kek_id); } function addMigrator(address migrator_address) external onlyByOwner { valid_migrators[migrator_address] = true; } function removeMigrator(address migrator_address) external onlyByOwner { require(valid_migrators[migrator_address] == true, "Address nonexistant"); delete valid_migrators[migrator_address]; } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } if (isRewardToken && rewardManagers[tokenAddress] == msg.sender){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else if (!isRewardToken && (msg.sender == owner)){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else { revert("No valid tokens to recover"); } } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } if (isRewardToken && rewardManagers[tokenAddress] == msg.sender){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else if (!isRewardToken && (msg.sender == owner)){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else { revert("No valid tokens to recover"); } } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } if (isRewardToken && rewardManagers[tokenAddress] == msg.sender){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else if (!isRewardToken && (msg.sender == owner)){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else { revert("No valid tokens to recover"); } } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } if (isRewardToken && rewardManagers[tokenAddress] == msg.sender){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else if (!isRewardToken && (msg.sender == owner)){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else { revert("No valid tokens to recover"); } } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } if (isRewardToken && rewardManagers[tokenAddress] == msg.sender){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else if (!isRewardToken && (msg.sender == owner)){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else { revert("No valid tokens to recover"); } } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } if (isRewardToken && rewardManagers[tokenAddress] == msg.sender){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else if (!isRewardToken && (msg.sender == owner)){ ERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(msg.sender, tokenAddress, tokenAmount); return; } else { revert("No valid tokens to recover"); } } function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwner { require(_rewardsDuration >= 86400, "Rewards duration too short"); require( periodFinish == 0 || block.timestamp > periodFinish, "Reward period incomplete" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } function setMultipliers(uint256 _lock_max_multiplier, uint256 _vefxs_max_multiplier, uint256 _vefxs_per_frax_for_max_boost) external onlyByOwner { require(_lock_max_multiplier >= MULTIPLIER_PRECISION, "Mult must be >= MULTIPLIER_PRECISION"); require(_vefxs_max_multiplier >= 0, "veFXS mul must be >= 0"); require(_vefxs_per_frax_for_max_boost > 0, "veFXS pct max must be >= 0"); lock_max_multiplier = _lock_max_multiplier; vefxs_max_multiplier = _vefxs_max_multiplier; vefxs_per_frax_for_max_boost = _vefxs_per_frax_for_max_boost; emit MaxVeFXSMultiplier(vefxs_max_multiplier); emit LockedStakeMaxMultiplierUpdated(lock_max_multiplier); emit veFXSPerFraxForMaxBoostUpdated(vefxs_per_frax_for_max_boost); } function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _lock_time_for_max_multiplier, uint256 _lock_time_min) external onlyByOwner { require(_lock_time_for_max_multiplier >= 1, "Mul max time must be >= 1"); require(_lock_time_min >= 1, "Mul min time must be >= 1"); lock_time_for_max_multiplier = _lock_time_for_max_multiplier; lock_time_min = _lock_time_min; emit LockedStakeTimeForMaxMultiplier(lock_time_for_max_multiplier); emit LockedStakeMinTime(_lock_time_min); } function greylistAddress(address _address) external onlyByOwner { greylist[_address] = !(greylist[_address]); } function unlockStakes() external onlyByOwner { stakesUnlocked = !stakesUnlocked; } function toggleStaking() external onlyByOwner { stakingPaused = !stakingPaused; } function toggleMigrations() external onlyByOwner { migrationsOn = !migrationsOn; } function toggleWithdrawals() external onlyByOwner { withdrawalsPaused = !withdrawalsPaused; } function toggleRewardsCollection() external onlyByOwner { rewardsCollectionPaused = !rewardsCollectionPaused; } function setRewardRate(address reward_token_address, uint256 new_rate, bool sync_too) external onlyTknMgrs(reward_token_address) { rewardRatesManual[rewardTokenAddrToIdx[reward_token_address]] = new_rate; if (sync_too){ sync(); } } function setRewardRate(address reward_token_address, uint256 new_rate, bool sync_too) external onlyTknMgrs(reward_token_address) { rewardRatesManual[rewardTokenAddrToIdx[reward_token_address]] = new_rate; if (sync_too){ sync(); } } function setGaugeController(address reward_token_address, address _rewards_distributor_address, address _gauge_controller_address, bool sync_too) external onlyTknMgrs(reward_token_address) { gaugeControllers[rewardTokenAddrToIdx[reward_token_address]] = _gauge_controller_address; rewards_distributor = IFraxGaugeFXSRewardsDistributor(_rewards_distributor_address); if (sync_too){ sync(); } } function setGaugeController(address reward_token_address, address _rewards_distributor_address, address _gauge_controller_address, bool sync_too) external onlyTknMgrs(reward_token_address) { gaugeControllers[rewardTokenAddrToIdx[reward_token_address]] = _gauge_controller_address; rewards_distributor = IFraxGaugeFXSRewardsDistributor(_rewards_distributor_address); if (sync_too){ sync(); } } function changeTokenManager(address reward_token_address, address new_manager_address) external onlyTknMgrs(reward_token_address) { rewardManagers[reward_token_address] = new_manager_address; } event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address); event WithdrawLocked(address indexed user, uint256 amount, bytes32 kek_id, address destination_address); event RewardPaid(address indexed user, uint256 reward, address token_address, address destination_address); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address destination_address, address token, uint256 amount); event RewardsPeriodRenewed(address token); event LockedStakeMaxMultiplierUpdated(uint256 multiplier); event LockedStakeTimeForMaxMultiplier(uint256 secs); event LockedStakeMinTime(uint256 secs); event MaxVeFXSMultiplier(uint256 multiplier); event veFXSPerFraxForMaxBoostUpdated(uint256 scale_factor); }
7,806,820
[ 1, 5361, 12146, 6062, 8350, 8805, 12146, 6062, 611, 17, 10377, 13102, 984, 77, 2864, 1071, 384, 6159, 1345, 31, 312, 30915, 467, 8141, 264, 2864, 1071, 384, 6159, 1345, 31, 8349, 1584, 44, 17, 42, 354, 92, 6426, 17329, 934, 911, 18485, 17329, 467, 510, 911, 11412, 12003, 1071, 384, 6159, 1345, 31, 1351, 291, 91, 438, 776, 22, 467, 984, 291, 91, 438, 58, 22, 4154, 1071, 384, 6159, 1345, 31, 19134, 18753, 14583, 2501, 10551, 364, 11191, 13382, 12682, 2647, 11093, 3488, 813, 471, 15027, 1947, 10489, 25172, 55, 3746, 534, 359, 1060, 6138, 16, 13335, 6138, 16, 19890, 17544, 16, 471, 19890, 21103, 534, 359, 1060, 3879, 534, 359, 1060, 11093, 30918, 11093, 987, 434, 923, 4196, 3062, 261, 542, 635, 314, 1643, 82, 1359, 13, 934, 581, 414, 444, 1492, 30188, 12, 87, 13, 2898, 2545, 358, 999, 1351, 291, 91, 438, 776, 22, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 934, 6159, 17631, 14727, 5002, 18941, 353, 14223, 11748, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 4232, 39, 3462, 31, 203, 203, 203, 565, 467, 537, 25172, 55, 3238, 10489, 25172, 55, 273, 467, 537, 25172, 55, 12, 20, 6511, 5193, 2643, 69, 42, 4449, 8204, 2246, 449, 37, 5608, 73, 5908, 23508, 29, 6743, 23, 2954, 4630, 23508, 26, 69, 5528, 25, 70, 20, 1769, 203, 203, 203, 377, 203, 203, 565, 1665, 84, 878, 2173, 84, 12003, 1071, 384, 6159, 1345, 31, 203, 203, 203, 203, 203, 565, 11083, 354, 92, 18941, 25172, 10090, 359, 14727, 1669, 19293, 1071, 283, 6397, 67, 2251, 19293, 31, 203, 203, 565, 1758, 3238, 5381, 284, 354, 92, 67, 2867, 273, 374, 92, 7140, 23, 72, 29, 2539, 69, 1441, 74, 24532, 4331, 6260, 28, 24008, 28, 3361, 6162, 2499, 2056, 4700, 42, 4033, 25, 70, 2733, 73, 31, 203, 377, 203, 565, 2254, 5034, 3238, 5381, 31385, 2053, 654, 67, 3670, 26913, 273, 404, 73, 2643, 31, 203, 203, 565, 2254, 5034, 1071, 3879, 11641, 31, 203, 565, 2254, 5034, 1071, 1142, 1891, 950, 31, 203, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 537, 74, 13713, 23365, 18005, 31, 203, 203, 565, 1758, 8526, 1071, 19890, 5157, 31, 203, 565, 1758, 8526, 1071, 13335, 13745, 31, 203, 565, 2254, 5034, 8526, 1071, 19890, 20836, 25139, 31, 203, 565, 533, 8526, 1071, 19890, 14821, 2 ]
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY529() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF13(address account) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER435(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE394(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE986(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM269(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER438(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL435(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER893() 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 TOTALSUPPLY529() public view returns (uint) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF13(address account) public view returns (uint) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER435(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER442(_MSGSENDER893(), recipient, amount); return true; } function ALLOWANCE394(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE986(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE356(_MSGSENDER893(), spender, amount); return true; } function TRANSFERFROM269(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER442(sender, recipient, amount); _APPROVE356(sender, _MSGSENDER893(), _allowances[sender][_MSGSENDER893()].SUB413(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE48(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE356(_MSGSENDER893(), spender, _allowances[_MSGSENDER893()][spender].ADD247(addedValue)); return true; } function DECREASEALLOWANCE388(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE356(_MSGSENDER893(), spender, _allowances[_MSGSENDER893()][spender].SUB413(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER442(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].SUB413(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD247(amount); emit TRANSFER438(sender, recipient, amount); } function _MINT106(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD247(amount); _balances[account] = _balances[account].ADD247(amount); emit TRANSFER438(address(0), account, amount); } function _BURN218(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB413(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB413(amount); emit TRANSFER438(account, address(0), amount); } function _APPROVE356(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 APPROVAL435(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 NAME365() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL877() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS902() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } library SafeMath { function ADD247(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB413(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB413(a, b, "SafeMath: subtraction overflow"); } function SUB413(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 MUL770(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 DIV5(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV5(a, b, "SafeMath: division by zero"); } function DIV5(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 ISCONTRACT572(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 SAFETRANSFER844(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN356(token, abi.encodeWithSelector(token.TRANSFER435.selector, to, value)); } function SAFETRANSFERFROM836(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN356(token, abi.encodeWithSelector(token.TRANSFERFROM269.selector, from, to, value)); } function SAFEAPPROVE865(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE394(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN356(token, abi.encodeWithSelector(token.APPROVE986.selector, spender, value)); } function CALLOPTIONALRETURN356(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT572(), "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 WAND 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("wand.finance", "WAND", 18) { governance = msg.sender; } function MINT7(address account, uint amount) public { //inject NONSTANDARD NAMING require(minters[msg.sender], "!minter"); _MINT106(account, amount); } function SETGOVERNANCE860(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function ADDMINTER132(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = true; } function REMOVEMINTER499(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = false; } }
inject NONSTANDARD NAMING
function ADD247(uint a, uint b) internal pure returns (uint) {
1,780,085
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11689, 3247, 27, 12, 11890, 279, 16, 2254, 324, 13, 2713, 16618, 1135, 261, 11890, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.6.0 <= 0.6.8; import "github.com/morozov1one/bfs/blob/master/solidity/source/Admin.sol"; contract Transfer_money { function send(address payable recipient) external payable { recipient.transfer(msg.value); } } contract Main { address private owner; address payable constant bfs_wallet = 0x0da52A47b11fFFefEf609E41FCF956b52ca9a2Ef; address constant admin_address = 0x3b1C4370D52692dFfbe0cFC9C2cc0935b0d0f747; uint64[4] private subs_days; //how many subscription days are left uint256[4] private last_upd; //latest update User private user; Banker private banker; Business private business; Investor private investor; Transfer_money private tm; event ConstructorInitiated(string nextStep); event Deposit(address _sender, uint amount); event Withdraw(address _sender, uint amount, address recipient); constructor () public { emit ConstructorInitiated("constructor Main"); Admin admin = Admin(admin_address); require(!admin.checkUser(msg.sender)); owner = msg.sender; subs_days[0] = 0; subs_days[1] = 0; subs_days[2] = 0; subs_days[3] = 0; last_upd[0] = now; last_upd[1] = now; last_upd[2] = now; last_upd[3] = now; tm = new Transfer_money(); } function createProfiles() public { require(msg.sender == owner); user = new User(address(this)); banker = new Banker(address(this)); business = new Business(address(this)); investor = new Investor(address(this)); } function getOwner() external view returns (address) { return owner; } function getAddress() external view returns(address) { return address(this); } function getUserAddress() external view returns(address) { return address(user); } function getBankerAddress() external view returns(address) { return address(banker); } function getBusinessAddress() external view returns(address) { return address(business); } function getInvestorAddress() external view returns(address) { return address(investor); } function getDays(uint8 profile) public view returns(uint64) { return subs_days[profile]; } function delDays(uint8 profile) public returns(uint256) { subs_days[profile] -= uint64((now - last_upd[profile]) / 86400); if (subs_days[profile] < 0) subs_days[profile] = 0; } function addDays(uint64 s_months, uint8 profile) public payable { Admin admin = Admin(admin_address); uint64 price = s_months * admin.getPrice(profile); require(msg.value >= price); emit Withdraw(owner, price, bfs_wallet); tm.send(bfs_wallet); delDays(profile); subs_days[profile] += (s_months * 30); last_upd[profile] = now; } } contract User { address private owner; address main_address; Transfer_money tm; constructor (address main) public { owner = msg.sender; tm = new Transfer_money(); main_address = main; } function checkSubs(address user, uint8 profile) public returns(bool) { Main u = Main(user); u.delDays(profile); return (u.getDays(profile) > 0); } function sendMoney(address payable recipient) public payable { require(checkSubs(main_address, 0)); tm.send(recipient); } function setDeposit(address banker) public payable { require(checkSubs(main_address, 0)); Main m = Main(banker); Banker b = Banker(m.getBankerAddress()); tm.send(payable(m.getOwner())); b.setDeposit(main_address, msg.value); } function getMoneyFromDeposit(address banker) public payable { require(checkSubs(main_address, 0)); Main m = Main(banker); Banker b = Banker(m.getBankerAddress()); b.getMoneyFromDeposit(main_address); } function askCredit(address banker, uint256 value, uint8 percent, uint64 term) public { require(checkSubs(main_address, 0)); Main m = Main(banker); Banker b = Banker(m.getBankerAddress()); b.askCredit(main_address, value, percent, term); } function payCredit(address banker) external payable { require(checkSubs(main_address, 0)); Main m = Main(banker); Banker b = Banker(m.getBankerAddress()); tm.send(payable(m.getOwner())); b.payCredit(main_address, msg.value); } } contract Banker { address private owner; address constant admin_address = 0x3b1C4370D52692dFfbe0cFC9C2cc0935b0d0f747; address main_address; Transfer_money tm; struct debt { uint256 value; uint8 percent; uint64 term; uint256 last_pay; } struct deposit { bool open; uint256 value; uint8 percent; uint16 term; uint256 last_upd; } address[] private list_of_credits; mapping(address => deposit) private deposits; mapping(address => debt) private credits; mapping(address => debt) private ask_credits; address payable[] private list_of_deposits; constructor (address main) public { owner = msg.sender; tm = new Transfer_money(); main_address = main; } function checkSubs(address user, uint8 profile) public returns(bool) { Main u = Main(user); u.delDays(profile); return (u.getDays(profile) > 0); } function getDeposit(address client, uint8 percent, uint16 term) public { require(msg.sender == owner); require(checkSubs(main_address, 1)); require(term > 0); deposits[client].open = true; deposits[client].last_upd = now; deposits[client].percent = percent; deposits[client].term = term; } function getPercents() public { require(deposits[msg.sender].open == true); uint16 count = uint16((now - deposits[msg.sender].last_upd) / 86400 / deposits[msg.sender].term); for (uint16 i = 0; i < count; ++i) deposits[msg.sender].value += (deposits[msg.sender].value * deposits[msg.sender].percent / 100); deposits[msg.sender].last_upd = now; } function getPercents(address client) public { require(msg.sender == owner); require(deposits[client].open == true); uint16 count = uint16((now - deposits[client].last_upd) / 86400 / deposits[client].term); for (uint16 i = 0; i < count; ++i) deposits[client].value += (deposits[client].value * deposits[client].percent / 100); deposits[client].last_upd = now; } function getMoneyFromDeposit(address client) external { Admin admin = Admin(admin_address); require(!admin.checkUser(msg.sender, client)); require(deposits[msg.sender].open == true); list_of_deposits.push(msg.sender); } function returnMoney() public payable { require(msg.sender == owner); for (uint16 i = 0; i < list_of_deposits.length; ++i) { getPercents(address(list_of_deposits[i])); tm.send(list_of_deposits[i]); } list_of_deposits = new address payable[](0); } function setDeposit(address user, uint256 value) external payable { Admin admin = Admin(admin_address); require(!admin.checkUser(msg.sender, user)); require(deposits[msg.sender].open == true); getPercents(); deposits[msg.sender].value += value; } function askCredit(address user, uint256 value, uint8 percent, uint64 term) external { Admin admin = Admin(admin_address); require(!admin.checkUser(msg.sender, user)); require(credits[msg.sender].value == 0); ask_credits[msg.sender].value = value; ask_credits[msg.sender].percent = percent; ask_credits[msg.sender].term = term; } function getCredit(address client, uint256 value, uint8 percent, uint64 term) public { require(msg.sender == owner); require(checkSubs(main_address, 1)); require(ask_credits[client].value == value); require(ask_credits[client].percent == percent); require(ask_credits[client].term == term); credits[client].value = value; credits[client].percent = percent; credits[client].term = term; credits[client].last_pay = now; list_of_credits.push(client); tm.send(payable(client)); } function checkOneCredit(address client) public { require(credits[client].value > 0); uint16 count = uint16((now - credits[client].last_pay) / 86400 / credits[client].term); for (uint16 j = 0; j < count; ++j) credits[client].value += (credits[client].value * credits[client].percent / 100); credits[client].last_pay = now; } function checkCredits() public { require(msg.sender == owner); require(checkSubs(main_address, 1)); for (uint16 i = 0; i < list_of_credits.length; ++i) checkOneCredit(list_of_credits[i]); } function howMuchCredit(address client) public returns(uint256) { require(credits[msg.sender].value > 0); checkOneCredit(client); return credits[client].value; } function payCredit(address user, uint256 value) external payable { Admin admin = Admin(admin_address); require(!admin.checkUser(msg.sender, user)); checkOneCredit(msg.sender); require(value >= credits[msg.sender].value); credits[msg.sender].value = 0; } } /* The implementation of contracts for business and investors cannot be written within the framework of a training project, since we cannot issue securities. This functionality can be perceived as a project development perspective */ contract Business { address private owner; address main_address; Transfer_money tm; constructor (address main) public { owner = msg.sender; tm = new Transfer_money(); main_address = main; } } contract Investor { address private owner; address main_address; Transfer_money tm; constructor (address main) public { owner = msg.sender; tm = new Transfer_money(); main_address = main; } }
how many subscription days are left
uint64[4] private subs_days;
12,944,977
[ 1, 13606, 4906, 4915, 4681, 854, 2002, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1105, 63, 24, 65, 3238, 11630, 67, 9810, 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 ]
./partial_match/42220/0x553a2a1B70725C1042A0D76e16f4f5a683648dEB/sources/src/interfaces/IWormhole.sol
@title IWormhole @author The Wormhole Team @notice A trimmed version of the core Wormhole contract interface @dev https://github.com/wormhole-foundation/wormhole/blob/44273c06417ce858d092d8a007359d5119f44ddb/ethereum/contracts/interfaces/IWormhole.sol#L4
interface IWormhole { pragma solidity ^0.8.13; struct Signature { bytes32 r; bytes32 s; uint8 v; uint8 guardianIndex; } struct VM { uint8 version; uint32 timestamp; uint32 nonce; uint16 emitterChainId; bytes32 emitterAddress; uint64 sequence; uint8 consistencyLevel; bytes payload; uint32 guardianSetIndex; Signature[] signatures; bytes32 hash; } }
3,497,983
[ 1, 45, 59, 535, 27167, 225, 1021, 678, 535, 27167, 10434, 225, 432, 12350, 1177, 434, 326, 2922, 678, 535, 27167, 6835, 1560, 225, 2333, 2207, 6662, 18, 832, 19, 91, 535, 27167, 17, 30493, 19, 91, 535, 27167, 19, 10721, 19, 6334, 5324, 23, 71, 20, 1105, 4033, 311, 7140, 28, 72, 5908, 22, 72, 28, 69, 713, 27, 4763, 29, 72, 25, 23635, 74, 6334, 449, 70, 19, 546, 822, 379, 19, 16351, 87, 19, 15898, 19, 45, 59, 535, 27167, 18, 18281, 48, 24, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 59, 535, 27167, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 3437, 31, 203, 565, 1958, 9249, 288, 203, 3639, 1731, 1578, 436, 31, 203, 3639, 1731, 1578, 272, 31, 203, 3639, 2254, 28, 331, 31, 203, 3639, 2254, 28, 11026, 2779, 1016, 31, 203, 565, 289, 203, 203, 565, 1958, 8251, 288, 203, 3639, 2254, 28, 1177, 31, 203, 3639, 2254, 1578, 2858, 31, 203, 3639, 2254, 1578, 7448, 31, 203, 3639, 2254, 2313, 11520, 3893, 548, 31, 203, 3639, 1731, 1578, 11520, 1887, 31, 203, 3639, 2254, 1105, 3102, 31, 203, 3639, 2254, 28, 14297, 2355, 31, 203, 3639, 1731, 2385, 31, 203, 3639, 2254, 1578, 11026, 2779, 694, 1016, 31, 203, 3639, 9249, 8526, 14862, 31, 203, 3639, 1731, 1578, 1651, 31, 203, 565, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "@openzeppelin/contracts//ownership/Ownable.sol"; // only the interface code from the current file is used in the bridge contract(RainbowOnes.sol) // contract code deployed from elc/ethClient is actually set using changeLightClient method in RainbowOnes.sol. interface ILightClient { function VerifyReceiptsHash(bytes32 blockHash, bytes32 receiptsHash) external returns(bool); } contract LightClientUnsafe is ILightClient { function VerifyReceiptsHash(bytes32 blockHash, bytes32 receiptsHash) public returns(bool) { blockHash;receiptsHash; return true; } } contract LightClientTrust is ILightClient,Ownable { constructor() Ownable() public {} mapping(bytes32=>bytes32) public Receipts; function VerifyReceiptsHash(bytes32 blockHash, bytes32 receiptsHash) public returns(bool) { return Receipts[blockHash] == receiptsHash; } function FeedReeipts(bytes32 blockHash, bytes32 receiptsHash) public onlyOwner { Receipts[blockHash] = receiptsHash; } }
only the interface code from the current file is used in the bridge contract(RainbowOnes.sol) contract code deployed from elc/ethClient is actually set using changeLightClient method in RainbowOnes.sol.
interface ILightClient { function VerifyReceiptsHash(bytes32 blockHash, bytes32 receiptsHash) external returns(bool); }
12,889,025
[ 1, 3700, 326, 1560, 981, 628, 326, 783, 585, 353, 1399, 316, 326, 10105, 6835, 12, 54, 530, 70, 543, 1398, 281, 18, 18281, 13, 6835, 981, 19357, 628, 415, 71, 19, 546, 1227, 353, 6013, 444, 1450, 2549, 12128, 1227, 707, 316, 534, 530, 70, 543, 1398, 281, 18, 18281, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 5831, 467, 12128, 1227, 288, 203, 565, 445, 8553, 4779, 27827, 2310, 12, 3890, 1578, 31493, 16, 1731, 1578, 2637, 27827, 2310, 13, 3903, 1135, 12, 6430, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xdE105650003B381FE9C862F7bDaBC3ce8CB11d76/sources/contracts/FCNVault.sol
* Redeem a given amount of shares in return for assets Shares are burned from the caller @param shares is the amount of shares (vault tokens) to be redeemed/
function redeem(uint256 shares) external onlyOwner returns (uint256) { uint256 assets = convertToAssets(shares); _burn(msg.sender, shares); return assets; }
4,010,910
[ 1, 426, 24903, 279, 864, 3844, 434, 24123, 316, 327, 364, 7176, 2638, 4807, 854, 18305, 329, 628, 326, 4894, 225, 24123, 353, 326, 3844, 434, 24123, 261, 26983, 2430, 13, 358, 506, 283, 24903, 329, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 24903, 12, 11890, 5034, 24123, 13, 3903, 1338, 5541, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 7176, 273, 8137, 10726, 12, 30720, 1769, 203, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 24123, 1769, 203, 203, 3639, 327, 7176, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; import "./ERC20.sol"; contract AtomicSwapEtherToERC20 { struct Swap { uint256 value; address ethTrader; uint256 erc20Value; address erc20Trader; address erc20ContractAddress; } enum States { INVALID, OPEN, CLOSED, EXPIRED } mapping (bytes32 => Swap) private swaps; mapping (bytes32 => States) private swapStates; event Open(bytes32 _swapID, address _closeTrader); event Expire(bytes32 _swapID); event Close(bytes32 _swapID); modifier onlyInvalidSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.INVALID); _; } modifier onlyOpenSwaps(bytes32 _swapID) { require (swapStates[_swapID] == States.OPEN); _; } function open(bytes32 _swapID, uint256 _erc20Value, address _erc20Trader, address _erc20ContractAddress) public onlyInvalidSwaps(_swapID) payable { // Store the details of the swap. Swap memory swap = Swap({ value: msg.value, ethTrader: msg.sender, erc20Value: _erc20Value, erc20Trader: _erc20Trader, erc20ContractAddress: _erc20ContractAddress }); swaps[_swapID] = swap; swapStates[_swapID] = States.OPEN; Open(_swapID, _erc20Trader); } function close(bytes32 _swapID) public onlyOpenSwaps(_swapID) { // Close the swap. Swap memory swap = swaps[_swapID]; swapStates[_swapID] = States.CLOSED; // Transfer the ERC20 funds from the ERC20 trader to the ETH trader. ERC20 erc20Contract = ERC20(swap.erc20ContractAddress); require(swap.erc20Value <= erc20Contract.allowance(swap.erc20Trader, address(this))); require(erc20Contract.transferFrom(swap.erc20Trader, swap.ethTrader, swap.erc20Value)); // Transfer the ETH funds from this contract to the ERC20 trader. swap.erc20Trader.transfer(swap.value); Close(_swapID); } function expire(bytes32 _swapID) public onlyOpenSwaps(_swapID) { // Expire the swap. Swap memory swap = swaps[_swapID]; swapStates[_swapID] = States.EXPIRED; // Transfer the ETH value from this contract back to the ETH trader. swap.ethTrader.transfer(swap.value); Expire(_swapID); } function check(bytes32 _swapID) public view returns (uint256 value, uint256 erc20Value, address erc20Trader, address erc20ContractAddress) { Swap memory swap = swaps[_swapID]; return (swap.value, swap.erc20Value, swap.erc20Trader, swap.erc20ContractAddress); } }
Store the details of the swap.
function open(bytes32 _swapID, uint256 _erc20Value, address _erc20Trader, address _erc20ContractAddress) public onlyInvalidSwaps(_swapID) payable { Swap memory swap = Swap({ value: msg.value, ethTrader: msg.sender, erc20Value: _erc20Value, erc20Trader: _erc20Trader, erc20ContractAddress: _erc20ContractAddress }); swaps[_swapID] = swap; swapStates[_swapID] = States.OPEN; Open(_swapID, _erc20Trader); }
12,913,049
[ 1, 2257, 326, 3189, 434, 326, 7720, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1696, 12, 3890, 1578, 389, 22270, 734, 16, 2254, 5034, 389, 12610, 3462, 620, 16, 1758, 389, 12610, 3462, 1609, 765, 16, 1758, 389, 12610, 3462, 8924, 1887, 13, 1071, 1338, 1941, 6050, 6679, 24899, 22270, 734, 13, 8843, 429, 288, 203, 565, 12738, 3778, 7720, 273, 12738, 12590, 203, 1377, 460, 30, 1234, 18, 1132, 16, 203, 1377, 13750, 1609, 765, 30, 1234, 18, 15330, 16, 203, 1377, 6445, 71, 3462, 620, 30, 389, 12610, 3462, 620, 16, 203, 1377, 6445, 71, 3462, 1609, 765, 30, 389, 12610, 3462, 1609, 765, 16, 203, 1377, 6445, 71, 3462, 8924, 1887, 30, 389, 12610, 3462, 8924, 1887, 203, 565, 15549, 203, 565, 1352, 6679, 63, 67, 22270, 734, 65, 273, 7720, 31, 203, 565, 7720, 7629, 63, 67, 22270, 734, 65, 273, 29577, 18, 11437, 31, 203, 203, 565, 3502, 24899, 22270, 734, 16, 389, 12610, 3462, 1609, 765, 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 ]
./full_match/4/0xeE76834ca4690B4A1dfb6DFAc5202EC29572c216/sources/mnt/d/Lab/nft/truffle-verify-contract/verify-contract/truffle-plugin-verify/docs/kalis-me-tutorial-code/contracts/TransferProxy.sol
* @dev Constructor function/ register the supported interfaces to conform to ERC721 via ERC165
constructor (string memory _name, string memory _symbol, string memory contractURI, string memory _tokenURIPrefix) HasContractURI(contractURI) HasTokenURI(_tokenURIPrefix) public { name = _name; symbol = _symbol; _registerInterface(_INTERFACE_ID_ERC721_METADATA); }
664,103
[ 1, 6293, 445, 19, 1744, 326, 3260, 7349, 358, 20156, 358, 4232, 39, 27, 5340, 3970, 4232, 39, 28275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 261, 1080, 3778, 389, 529, 16, 533, 3778, 389, 7175, 16, 533, 3778, 6835, 3098, 16, 533, 3778, 389, 2316, 3098, 2244, 13, 4393, 8924, 3098, 12, 16351, 3098, 13, 4393, 1345, 3098, 24899, 2316, 3098, 2244, 13, 1071, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 273, 389, 7175, 31, 203, 203, 3639, 389, 4861, 1358, 24899, 18865, 67, 734, 67, 654, 39, 27, 5340, 67, 22746, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-02 */ /** *Submitted for verification at Etherscan.io on 2021-10-27 */ pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; struct slice { uint _len; uint _ptr; } /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for *; // 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().toSlice().concat('.json'.toSlice()))) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract kryptoGangsters is Ownable, ERC721 { using Counters for Counters.Counter; using Strings for *; Counters.Counter public _tokenIDs; mapping(address => bool) public isAdmin; mapping(address => bool) public isWhiteListed; mapping(address => uint256) public tokenCounters; string public baseTokenURI; uint256 private mintAmount = 0.1 ether; uint256 private mintWhitelistAmount = 0.08 ether; constructor() ERC721("KRYPTO GANGSTERS", "GANGSTERS") { } modifier onlyMinter() { require( isAdmin[_msgSender()] || owner() == _msgSender() || isWhiteListed[_msgSender()], " caller has no minting right!!!" ); _; } modifier onlyAdmin() { require( isAdmin[_msgSender()] || owner() == _msgSender(), " caller has no minting right!!!" ); _; } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function createItem(uint256 amount) public payable { require(_tokenIDs.current() + amount <= 10000, "Max mint amount is reached"); require( tokenCounters[msg.sender] + amount <= 20, "Regular member can only 20 NFT tokens at max" ); if (isWhiteListed[msg.sender]){ require(amount * mintWhitelistAmount == msg.value, "You sent the incorrect amount of tokens"); }else{ require(amount * mintAmount == msg.value, "You sent the incorrect amount of tokens"); } for (uint256 i = 0; i < amount; i++) { _tokenIDs.increment(); uint256 newItemID = _tokenIDs.current(); _safeMint(msg.sender , newItemID); } tokenCounters[msg.sender] = tokenCounters[msg.sender] + amount; } function createTeamItem(address owner) private { for (uint256 i = 0; i < 5; i++) { require(_tokenIDs.current() <= 10000, "Max mint amount is reached"); _tokenIDs.increment(); uint256 newItemID = _tokenIDs.current(); _safeMint(owner , newItemID); } tokenCounters[owner] = 5; } function addAdmin(address adminAddress) public onlyOwner { require( adminAddress != address(0), " admin Address is the zero address" ); isAdmin[adminAddress] = true; } function removeAdmin(address adminAddress) public onlyOwner { require( adminAddress != address(0), " admin Address is the zero address" ); isAdmin[adminAddress] = false; } function blackListAddress(address userAddress) public onlyAdmin { require(userAddress != address(0), " userAddress is the zero address"); isWhiteListed[userAddress] = false; } function setRevealOpenSea(string memory baseURI) public onlyAdmin { baseTokenURI = baseURI; } function withdraw() public onlyAdmin { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function batchMintTeam(address[] memory teamList) public onlyAdmin { for (uint256 i = 0; i < teamList.length; i++) { createTeamItem(teamList[i]); } } function batchWhiteListAddress(address[] memory userAddresses) public onlyAdmin { for (uint i = 0; i < userAddresses.length; i++) { isWhiteListed[userAddresses[i]] = true; } } function setMintAmount(uint256 amount) public onlyOwner { mintAmount = amount; } function setMintWhitelistAmount(uint256 amount) public onlyOwner { mintWhitelistAmount = amount; } function uintToString(uint256 v) internal pure returns (string memory str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = bytes1(uint8(48 + remainder)); } bytes memory s = new bytes(i + 1); for (uint j = 0; j <= i; j++) { s[j] = reversed[i - j]; } str = string(s); return str; } }
* @dev Initializes the contract setting the deployer as the initial owner./
function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; constructor() { _setOwner(_msgSender()); }
2,281,877
[ 1, 9685, 326, 6835, 3637, 326, 7286, 264, 487, 326, 2172, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 3885, 1435, 288, 203, 3639, 389, 542, 5541, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xC8CdB0A09141881F3B8b55Cca5AaAD2c7B711684/sources/Funded.sol
If any account belongs to _isExcludedFromFee account then remove the fee Only take fees on buys/sells, do not take on wallet transfers Sell Buy
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(!blacklisted[from],"Sender blacklisted"); require(!blacklisted[to],"Receiver blacklisted"); if (amount == 0) { super._transfer(from, to, 0); return; } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = (amount * sellTotalFees) / 100; tokensForFundedAccounts += (fees * sellFundedAccountsFee) / sellTotalFees; tokensForRevShare += (fees * sellRevShareFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = (amount * buyTotalFees) / 100; tokensForFundedAccounts += (fees * buyFundedAccountsFee) / buyTotalFees; tokensForRevShare += (fees * buyRevShareFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); }
15,567,217
[ 1, 2047, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 5098, 4862, 1656, 281, 603, 25666, 1900, 19, 87, 1165, 87, 16, 741, 486, 4862, 603, 9230, 29375, 348, 1165, 605, 9835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 5, 11223, 18647, 63, 2080, 6487, 6, 12021, 25350, 8863, 203, 3639, 2583, 12, 5, 11223, 18647, 63, 869, 6487, 6, 12952, 25350, 8863, 203, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 374, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 203, 7734, 628, 480, 3410, 1435, 597, 203, 7734, 358, 480, 3410, 1435, 597, 203, 7734, 358, 480, 1758, 12, 20, 13, 597, 203, 7734, 358, 480, 1758, 12, 20, 92, 22097, 13, 597, 203, 7734, 401, 22270, 1382, 203, 5411, 262, 288, 203, 7734, 309, 16051, 313, 14968, 3896, 13, 288, 203, 10792, 2583, 12, 203, 13491, 389, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 747, 389, 291, 16461, 1265, 2954, 281, 63, 869, 6487, 203, 13491, 315, 1609, 7459, 353, 486, 2695, 1199, 203, 10792, 11272, 203, 7734, 289, 203, 203, 10792, 18472, 690, 3882, 278, 12373, 10409, 63, 2080, 65, 597, 203, 10792, 401, 67, 291, 16461, 2747, 3342, 6275, 63, 869, 65, 203, 7734, 262, 288, 203, 10792, 2583, 2 ]
./full_match/5/0xd6C7de94DAf24b947288F74f40323f13Fe83eFB0/sources/contracts/cryptodeposit.sol
user(as owner) needs to give approval to this contract (spender) in USDZ contract.
function depositTokenA(uint256 _amountInBits) public returns (bool) { require( tokenA.balanceOf(msg.sender) >= _amountInBits, "Not enough token balance" ); depositId++; int256 prices = getLatestPrice(); uint256 tokenADeopsit = _amountInBits; uint256 weiAmt = (tokenADeopsit * (10**12)) / uint256(prices); tokenA.transferFrom(msg.sender, address(this), tokenADeopsit); if(!firstTx[_msgSender()]) { address upline = viewMyUplinesAddress(); tokenA.transfer(_msgSender(), tokenADeopsit*introducerReward100x/10000); if(upline != address(0)) tokenA.transfer(upline, tokenADeopsit*introducerReward100x/10000); } depositData[msg.sender][depositId] = Deposit( uint32(block.timestamp), interestRate100x, tokenADeopsit, weiAmt, prices / (10**12) ); isActiveD[depositId] = true; myDeposits[msg.sender].push(depositId); emit Deposits(depositId, tokenADeopsit, 0); return true; }
11,586,384
[ 1, 1355, 12, 345, 3410, 13, 4260, 358, 8492, 23556, 358, 333, 6835, 261, 87, 1302, 264, 13, 316, 587, 9903, 62, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 1345, 37, 12, 11890, 5034, 389, 8949, 382, 6495, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 203, 5411, 1147, 37, 18, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 389, 8949, 382, 6495, 16, 203, 5411, 315, 1248, 7304, 1147, 11013, 6, 203, 3639, 11272, 203, 3639, 443, 1724, 548, 9904, 31, 203, 3639, 509, 5034, 19827, 273, 336, 18650, 5147, 5621, 203, 3639, 2254, 5034, 1147, 37, 758, 4473, 305, 273, 389, 8949, 382, 6495, 31, 203, 3639, 2254, 5034, 732, 77, 31787, 273, 261, 2316, 37, 758, 4473, 305, 380, 261, 2163, 636, 2138, 3719, 342, 2254, 5034, 12, 683, 1242, 1769, 203, 203, 3639, 1147, 37, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 1147, 37, 758, 4473, 305, 1769, 203, 203, 3639, 309, 12, 5, 3645, 4188, 63, 67, 3576, 12021, 1435, 5717, 288, 203, 5411, 1758, 582, 412, 558, 273, 1476, 12062, 57, 412, 1465, 1887, 5621, 203, 5411, 1147, 37, 18, 13866, 24899, 3576, 12021, 9334, 1147, 37, 758, 4473, 305, 14, 23342, 2544, 2750, 17631, 1060, 6625, 92, 19, 23899, 1769, 203, 5411, 309, 12, 89, 412, 558, 480, 1758, 12, 20, 3719, 203, 7734, 1147, 37, 18, 13866, 12, 89, 412, 558, 16, 1147, 37, 758, 4473, 305, 14, 23342, 2544, 2750, 17631, 1060, 6625, 92, 19, 23899, 1769, 203, 3639, 289, 203, 203, 203, 3639, 443, 1724, 751, 63, 3576, 18, 15330, 6362, 323, 1724, 548, 65, 273, 4019, 538, 305, 12, 203, 2 ]
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.2; import "./SafeMath.sol"; import "./Ownable.sol"; import "./IUniswapV2Pair.sol"; import "./IUniswapV2Factory.sol"; import "./IUniswapV2Router.sol"; import "./ERC20.sol"; import "./Address.sol"; import "./IERC20.sol"; contract LuckyDoge is ERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; mapping(address => bool) private _AddressExists; mapping(address => uint256) private avaliableBnb; address[] private _addressList; address[] private _excluded; address private _devWallet; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 2000 * 10 ** 8 * 10 ** 9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public _taxFee = 1; uint256 public _liquidityFee = 2; uint256 public _lottoFee = 2; uint256 public _fomoFee = 2; uint256 public _preFomoFee; uint256 public _devFee = 2; uint256 public _burnFee = 1; struct FomoWinner { address winner; uint256 amount; } struct LottoWinner { address winner; uint256 amount; } struct WaitingFomoWinner { address user; uint fomoAward; uint openFomoTime; } struct TData { uint tTransferAmount; uint tLiquidity; uint tLotto; uint tDev; uint tFomo; uint tBurn; uint tFee; } address public waitLottoWinner; LottoWinner[] public lottoWinnerList; bool public haveLastFomoBuy; WaitingFomoWinner public lastFomoBuyUser; FomoWinner[] public fomoWinnerList; uint256 public fomoIntervalTime = 3 minutes; uint256 public _minLottoBalance = 10000 * 10 ** 9; uint256 public _minFoMouyBuyUsdt = 10000000; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address public dogeAddress; address public constant DEAD = 0x0000000000000000000000000000000000000000; address public usdt; bool swapping; bool public swapAndLiquifyEnabled = true; bool public swapDogeEnabled = true; bool public swapLiquifyEnabled = true; bool public swapFomoEnabled = true; uint256 public _maxTxAmount = 20 * 10 ** 8 * 10 ** 9; uint256 public numTokensSellToAddToLiquidity = 2 * 10 ** 8 * 10 ** 9; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapDoge(uint256 tokenAmount, uint256 doge); event DrawLotto(uint256 amount, uint _lottoDrawCount); event SwapFomo(uint tokenAmount, uint bnb); event NewBuy(address user, uint amount); event FomoBuy(address user, uint amount); event SettleFomoAward(address winner, uint fomoAward); event SettleLottoAward(address winner, uint lottoAward); modifier lockTheSwap { swapping = true; _; swapping = false; } constructor(address _dogeAddress, address _routerAddress, address _usdt, address _devAddress) public ERC20("LUCKY DOGE", "LUD") { dogeAddress = _dogeAddress; usdt = _usdt; _devWallet = _devAddress; _rOwned[_msgSender()] = _rTotal; addAddress(_msgSender()); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_routerAddress); // 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; _approve(owner(), _routerAddress, MAX); _approve(address(this), _routerAddress, MAX); emit Transfer(address(0), _msgSender(), _tTotal); } function getFomoLength() public view returns(uint256){ return fomoWinnerList.length; } function getLottoLength() public view returns(uint256){ return lottoWinnerList.length; } function minLottoBalance() public view returns (uint256) { return _minLottoBalance; } function currentLottoPool() public view returns (uint256) { return IERC20(dogeAddress).balanceOf(address(this)); } function currentFomoPool() public view returns (uint256){ return avaliableBnb[address(this)]; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function isIncludeFromLotto(address account) public view returns (bool) { return _AddressExists[account]; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function settleFomo() public{ _settleFomo(msg.sender,0,false); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); uint256 rate = _getRate(); if (!deductTransferFee) { return tAmount.mul(rate); } else { uint256 tTransferAmount = _getTValues(tAmount).tTransferAmount; return tTransferAmount.mul(rate); } } 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 drawLotto() public onlyOwner { require(waitLottoWinner != address(0), "validate lotto winner address"); //swap doge uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance > 0) swapDogeAndLiquify(contractTokenBalance); uint lottoBalance = currentLottoPool(); require(lottoBalance > 0, "dont have enough Doge!"); address winner = waitLottoWinner; delete waitLottoWinner; IERC20(dogeAddress).transfer(winner, lottoBalance); lottoWinnerList.push(LottoWinner(winner, lottoBalance)); emit SettleLottoAward(winner, lottoBalance); } //random the lucky boy function lotterize() public onlyOwner returns (address) { uint256 randomNumber = random().mod(_addressList.length); uint256 ownedAmount = _rOwned[_addressList[randomNumber]]; if (ownedAmount >= _minLottoBalance) { waitLottoWinner = _addressList[randomNumber]; } else { waitLottoWinner = _devWallet; } return waitLottoWinner; } function excludeFromReward(address account) external 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 setUniswapRouter(address r) external onlyOwner { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(r); uniswapV2Router = _uniswapV2Router; } function setUniswapPair(address p) external onlyOwner { uniswapV2Pair = p; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFee(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLottoFee(uint256 lottoFee) external onlyOwner() { _lottoFee = lottoFee; } function setDevFee(uint256 devFee) external onlyOwner() { _devFee = devFee; } function setBurnFee(uint burnFee) external onlyOwner() { _burnFee = burnFee; } function setLiquidityFee(uint fee) external onlyOwner() { _liquidityFee = fee; } function setFomoFee(uint fee) external onlyOwner() { _fomoFee = fee; } function setDevAddress(address payable dev) external onlyOwner() { _devWallet = dev; } function setFoMouyBuyUsdt(uint256 minBalance) external onlyOwner() { _minFoMouyBuyUsdt = minBalance; } function setMinLottoBalance(uint256 minBalance) external onlyOwner() { _minLottoBalance = minBalance; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10 ** 2 ); } function setFomoIntervalTime(uint256 _seconds) external onlyOwner{ fomoIntervalTime = _seconds; } function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setSwapDogeEnabled(bool _enabled) external onlyOwner { swapDogeEnabled = _enabled; } function setSwapLiquifyEnabled(bool _enabled) external onlyOwner { swapLiquifyEnabled = _enabled; } function setNumTokensSellToAddToLiquidity(uint256 amount) external onlyOwner { numTokensSellToAddToLiquidity = amount; } function setSwapFomoEnabled(bool e) external onlyOwner { swapFomoEnabled = e; } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function random() private view returns (uint) { return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, block.number))); } 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 addAddress(address adr) private { if (_AddressExists[adr]) return; _AddressExists[adr] = true; _addressList.push(adr); } function _takeDev(uint256 tDev) private { uint256 currentRate = _getRate(); uint256 rDev = tDev.mul(currentRate); _rOwned[_devWallet] = _rOwned[_devWallet].add(rDev); if (_isExcluded[_devWallet]) _tOwned[_devWallet] = _tOwned[_devWallet].add(tDev); } function calculateAnyFee(uint256 _amount, uint256 _fee) private pure returns (uint256){ return _amount.mul(_fee).div( 10 ** 2 ); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "BEP20: transfer from the zero address"); require(to != address(0), "BEP20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if ( owner() != from && to != owner() && to == uniswapV2Pair //add liquidity ){ require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } address _this = address(this); addAddress(from); addAddress(to); uint256 contractTokenBalance = balanceOf(_this); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( swapAndLiquifyEnabled && overMinTokenBalance && !swapping && from != uniswapV2Pair && from != address(uniswapV2Router) && to != owner() && from != owner() ) { swapDogeAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = !swapping; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } address _router = address(uniswapV2Router); bool isSell = from != _router && to == uniswapV2Pair; uint _innerTransferAmount = amount; uint _innerTFee; if (takeFee) { bool swapFomo = isSell && swapFomoEnabled; if (!swapFomo) removeFomoFee(); TData memory data = _getTValues(amount); _innerTransferAmount = data.tTransferAmount; uint tLiquidity = data.tLiquidity; uint tLotto = data.tLotto; uint tDev = data.tDev; uint tFomo = data.tFomo; uint tBurn = data.tBurn; uint tFee = data.tFee; _takeLiquidityAndLottoAndFomo(tLiquidity, tLotto, tFomo); _takeDev(tDev); if (tFomo > 0 && !swapping) { // sell action swapForFomo(tFomo); } _takeBurn(tBurn); _innerTFee = tFee; if (!swapFomo) restoreFomoFee(); } _tokenTransfer(from, to, _innerTransferAmount); //reflect token if (_innerTFee > 0) _reflectFee(_innerTFee, _innerTFee.mul(_getRate())); if (!swapping) { //only buy bool isBuy = from == uniswapV2Pair && to != _router; _settleFomo(to, amount, isBuy); } } //swap doge to lotto pool function swapDogeAndLiquify(uint contractTokenBalance) private lockTheSwap { // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. //swap doge and add liquify uint256 _totalFees = _liquidityFee.add(_lottoFee); uint256 swapTokens = contractTokenBalance.mul(_liquidityFee).div(_totalFees); if (swapLiquifyEnabled) swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); if (swapDogeEnabled) swapTokensForDoge(sellTokens); } function removeFomoFee() private { if (_fomoFee == 0) return; _preFomoFee = _fomoFee; _fomoFee = 0; } function restoreFomoFee() private { _fomoFee = _preFomoFee; } //swap bnb to fomo pool function swapForFomo(uint256 token) private lockTheSwap { address _this = address(this); uint256 initialBalance = _this.balance; swapTokensForEth(token); uint256 newBalance = _this.balance.sub(initialBalance); avaliableBnb[_this] = avaliableBnb[_this].add(newBalance); emit SwapFomo(token, newBalance); } function _takeLiquidityAndLottoAndFomo(uint256 tLiquidity, uint256 tLotto, uint256 tFomo) private { uint256 tAmount = tLiquidity.add(tLotto).add(tFomo); uint256 rAmount = _getCurrentRateValue(tAmount); _rOwned[address(this)] = _rOwned[address(this)].add(rAmount); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tAmount); } function _takeBurn(uint256 tBurn) private { uint256 currentRate = _getRate(); uint256 rBurn = tBurn.mul(currentRate); address _d = DEAD; _rOwned[_d] = _rOwned[_d].add(rBurn); if (_isExcluded[_d]) _tOwned[_d] = _tOwned[_d].add(tBurn); } function _getCurrentRateValue(uint256 amount) private view returns (uint256 r){ r = amount.mul(_getRate()); } function _getTValues(uint256 tAmount) private view returns (TData memory) { uint tFee = calculateAnyFee(tAmount, _taxFee); uint256 tLiquidity = calculateAnyFee(tAmount, _liquidityFee); uint256 tLotto = calculateAnyFee(tAmount, _lottoFee); uint256 tDev = calculateAnyFee(tAmount, _devFee); uint256 tFomo = calculateAnyFee(tAmount, _fomoFee); uint256 tBurn = calculateAnyFee(tAmount, _burnFee); uint256 _t = tFee.add(tLiquidity).add(tLotto); _t = _t.add(tDev).add(tFomo).add(tBurn); uint tTransferAmount = tAmount.sub(_t); return TData(tTransferAmount, tLiquidity, tLotto, tDev, tFomo, tBurn, tFee); } //judge sell amount of usdt function canJoinFomoWin(uint256 amount) private view returns (bool){ address[] memory path = new address[](3); path[0] = address(this); path[1] = uniswapV2Router.WETH(); path[2] = usdt; uint[] memory amounts = uniswapV2Router.getAmountsOut(amount, path); return amounts.length > 0 && amounts[amounts.length - 1] >= _minFoMouyBuyUsdt; } function swapAndLiquify(uint256 contractTokenBalance) private { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } 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(); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function swapTokensForDoge(uint256 tokenAmount) private { address[] memory path = new address[](3); path[0] = address(this); path[1] = uniswapV2Router.WETH(); path[2] = dogeAddress; uint256 initialBalance = currentLottoPool(); uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); emit SwapDoge(tokenAmount, currentLottoPool().sub(initialBalance)); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // add the liquidity uniswapV2Router.addLiquidityETH{value : ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //settle fomo award function _settleFomo(address to, uint256 amount, bool isBuy) private { uint256 fomoPoolBalance = currentFomoPool(); //only add fomobuy when buy action and the pool balance is not zero and buy the min usdt bool canAddWaiting = isBuy && fomoPoolBalance > 0 && canJoinFomoWin(amount); if (isBuy) { if (canAddWaiting) emit FomoBuy(to, amount); else emit NewBuy(to, amount); } uint fomoTime = block.timestamp + fomoIntervalTime; if (haveLastFomoBuy && block.timestamp > lastFomoBuyUser.openFomoTime) { //maybe is sell haveLastFomoBuy = false; uint fomoAward = lastFomoBuyUser.fomoAward; address winner = lastFomoBuyUser.user; delete lastFomoBuyUser; avaliableBnb[address(this)] = fomoPoolBalance.sub((fomoAward)); //win record fomoWinnerList.push(FomoWinner(winner, fomoAward)); payable(winner).transfer(fomoAward); emit SettleFomoAward(winner, fomoAward); } // the last fomo buy user if (canAddWaiting) { haveLastFomoBuy = true; lastFomoBuyUser = WaitingFomoWinner(to, calculateAnyFee(currentFomoPool(), 40), fomoTime); } } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount) private { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { uint256 rAmount = tAmount.mul(_getRate()); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tAmount); _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { uint256 rAmount = tAmount.mul(_getRate()); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { uint256 rAmount = tAmount.mul(_getRate()); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tAmount); _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { uint256 rAmount = tAmount.mul(_getRate()); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } }
Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee
constructor(address _dogeAddress, address _routerAddress, address _usdt, address _devAddress) public ERC20("LUCKY DOGE", "LUD") { dogeAddress = _dogeAddress; usdt = _usdt; _devWallet = _devAddress; _rOwned[_msgSender()] = _rTotal; addAddress(_msgSender()); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_routerAddress); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _approve(owner(), _routerAddress, MAX); _approve(address(this), _routerAddress, MAX); emit Transfer(address(0), _msgSender(), _tTotal); }
12,869,606
[ 1, 1684, 279, 640, 291, 91, 438, 3082, 364, 333, 394, 1147, 444, 326, 3127, 434, 326, 6835, 3152, 10157, 3410, 471, 333, 6835, 628, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 12, 2867, 389, 20330, 73, 1887, 16, 1758, 389, 10717, 1887, 16, 1758, 389, 407, 7510, 16, 1758, 389, 5206, 1887, 13, 1071, 4232, 39, 3462, 2932, 11778, 3507, 61, 5467, 7113, 3113, 315, 11778, 40, 7923, 288, 203, 3639, 302, 717, 73, 1887, 273, 389, 20330, 73, 1887, 31, 203, 3639, 584, 7510, 273, 389, 407, 7510, 31, 203, 3639, 389, 5206, 16936, 273, 389, 5206, 1887, 31, 203, 203, 3639, 389, 86, 5460, 329, 63, 67, 3576, 12021, 1435, 65, 273, 389, 86, 5269, 31, 203, 3639, 527, 1887, 24899, 3576, 12021, 10663, 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, 24899, 10717, 1887, 1769, 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, 3639, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 8443, 1435, 65, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 203, 3639, 389, 12908, 537, 12, 8443, 9334, 389, 10717, 1887, 16, 4552, 1769, 203, 3639, 389, 12908, 537, 12, 2867, 12, 2 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.6.6; import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; // import 'hardhat/console.sol'; contract AutoBuy { using SafeMath for uint256; address haremToken; IUniswapV2Router02 uniswapRouterV2; IERC20 haremLPToken; constructor(address _haremToken, address _uniswapRouterV2, address _haremLPToken) public{ haremToken = _haremToken; uniswapRouterV2 = IUniswapV2Router02(_uniswapRouterV2); haremLPToken = IERC20(_haremLPToken); } function swapAndAddLiquidity(uint256 amount) public payable{ require(msg.value == amount.mul(2), 'Message value incorrect.'); // console.log(haremLPToken.balanceOf(address(this))); address[] memory path = new address[](2); path[0] = uniswapRouterV2.WETH(); path[1] = haremToken; uniswapRouterV2.swapExactETHForTokens.value(amount)(0, path, address(this), block.timestamp); // console.log(IERC20(haremToken).balanceOf(address(this))); IERC20(haremToken).approve(address(uniswapRouterV2), IERC20(haremToken).balanceOf(address(this))); uniswapRouterV2.addLiquidityETH.value(amount)(haremToken, IERC20(haremToken).balanceOf(address(this)), 0, 0, address(this), block.timestamp); // console.log(haremLPToken.balanceOf(address(this))); haremLPToken.transfer(msg.sender, IERC20(haremLPToken).balanceOf(address(this))); // console.log(haremLPToken.balanceOf(address(this))); // console.log(haremLPToken.balanceOf(msg.sender)); } } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
console.log(haremLPToken.balanceOf(address(this))); console.log(IERC20(haremToken).balanceOf(address(this))); console.log(haremLPToken.balanceOf(address(this))); console.log(haremLPToken.balanceOf(address(this))); console.log(haremLPToken.balanceOf(msg.sender));
function swapAndAddLiquidity(uint256 amount) public payable{ require(msg.value == amount.mul(2), 'Message value incorrect.'); address[] memory path = new address[](2); path[0] = uniswapRouterV2.WETH(); path[1] = haremToken; uniswapRouterV2.swapExactETHForTokens.value(amount)(0, path, address(this), block.timestamp); IERC20(haremToken).approve(address(uniswapRouterV2), IERC20(haremToken).balanceOf(address(this))); uniswapRouterV2.addLiquidityETH.value(amount)(haremToken, IERC20(haremToken).balanceOf(address(this)), 0, 0, address(this), block.timestamp); haremLPToken.transfer(msg.sender, IERC20(haremLPToken).balanceOf(address(this))); }
9,922,320
[ 1, 8698, 18, 1330, 12, 76, 834, 81, 14461, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 2983, 18, 1330, 12, 45, 654, 39, 3462, 12, 76, 834, 81, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 2983, 18, 1330, 12, 76, 834, 81, 14461, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 2983, 18, 1330, 12, 76, 834, 81, 14461, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 2983, 18, 1330, 12, 76, 834, 81, 14461, 1345, 18, 12296, 951, 12, 3576, 18, 15330, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7720, 1876, 986, 48, 18988, 24237, 12, 11890, 5034, 3844, 13, 1071, 8843, 429, 95, 203, 565, 2583, 12, 3576, 18, 1132, 422, 3844, 18, 16411, 12, 22, 3631, 296, 1079, 460, 11332, 1093, 1769, 203, 203, 565, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 565, 589, 63, 20, 65, 273, 640, 291, 91, 438, 8259, 58, 22, 18, 59, 1584, 44, 5621, 203, 565, 589, 63, 21, 65, 273, 366, 834, 81, 1345, 31, 7010, 565, 640, 291, 91, 438, 8259, 58, 22, 18, 22270, 14332, 1584, 44, 1290, 5157, 18, 1132, 12, 8949, 21433, 20, 16, 589, 16, 1758, 12, 2211, 3631, 1203, 18, 5508, 1769, 203, 203, 203, 565, 467, 654, 39, 3462, 12, 76, 834, 81, 1345, 2934, 12908, 537, 12, 2867, 12, 318, 291, 91, 438, 8259, 58, 22, 3631, 467, 654, 39, 3462, 12, 76, 834, 81, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 565, 640, 291, 91, 438, 8259, 58, 22, 18, 1289, 48, 18988, 24237, 1584, 44, 18, 1132, 12, 8949, 21433, 76, 834, 81, 1345, 16, 467, 654, 39, 3462, 12, 76, 834, 81, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 374, 16, 374, 16, 1758, 12, 2211, 3631, 1203, 18, 5508, 1769, 203, 203, 203, 565, 366, 834, 81, 14461, 1345, 18, 13866, 12, 3576, 18, 15330, 16, 467, 654, 39, 3462, 12, 76, 834, 81, 14461, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 225, 289, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract CCR is AccessControlEnumerable, ERC721Enumerable { using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; uint public constant MINT_PRICE = 0.04 ether; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint public constant _DEC_1_2021_16_00_00 = 1_638_345_600; string private _baseTokenURI; uint256 public _whitelistEndDate; uint256 public _maxSupply; address private _fundAddress; mapping (address => bool) public whitelist; mapping (address => uint) public minted; constructor(string memory baseTokenURI) ERC721("CryptoChasers Robot", "CCR"){ _maxSupply = 500; _fundAddress = msg.sender; _baseTokenURI = baseTokenURI; _whitelistEndDate = _DEC_1_2021_16_00_00; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); } // modifier admin has admin role can call this function modifier onlyAdmin { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Only admin can call function"); _; } // get token URL function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { return string(super.tokenURI(tokenId)); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } // admin can change baseTokenURI function setBaseTokenURI(string memory baseTokenURI) onlyAdmin external{ _baseTokenURI = baseTokenURI; } function _mintProxy(address to) internal { _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); minted[to] += 1; } // admin can direct mint NFT to any address function mintByAdmin(address[] calldata recievers) onlyAdmin external { require(_maxSupply >= totalSupply() + recievers.length, "Max supply reached"); for (uint i = 0; i < recievers.length; i++) { _mintProxy(recievers[i]); } } // Users will have to spend ETH to mint NFT // max mint 2 per sender // should set a blockheight, before height should verify if in whitelist, // after it any address can mint freely function mint() external payable { require(minted[msg.sender] < 2, "Max mint 2 per sender"); require(_maxSupply >= totalSupply(), "Max supply reached"); if(whitelist[msg.sender]) { require(hasRole(MINTER_ROLE, _msgSender()), "must have minter role to mint"); if(minted[msg.sender] == 0){ _mintProxy(msg.sender); }else{ require(msg.value == MINT_PRICE, "Need to send 0.04 ether"); _mintProxy(msg.sender); } } else{ require(block.timestamp >= _whitelistEndDate, "only in whitelist can mint now"); require(msg.value == MINT_PRICE, "Need to send 0.04 ether"); _mintProxy(msg.sender); } } // admin can set whitelistEndDate function setwhitelistEndDate(uint256 whitelistEndDate) onlyAdmin external { _whitelistEndDate = whitelistEndDate; } // admin can set maxSupply function setMaxSupply(uint256 maxSupply) onlyAdmin external { _maxSupply = maxSupply; } // admin can set addresses array as MINTER_ROLE function addToWhitelist(address[] memory _whiteListAddresses) onlyAdmin external { for (uint i = 0; i < _whiteListAddresses.length; i++) { whitelist[_whiteListAddresses[i]] = true; super.grantRole(MINTER_ROLE, _whiteListAddresses[i]); } } // check if address is in whitelist function isInWhitelist(address _address) external view returns (bool) { return whitelist[_address]; } // get remaining supply function getRemainingSupply() external view returns (uint256) { return _maxSupply - totalSupply(); } // get minted count function getMintedCount(address _address) external view returns (uint256) { return minted[_address]; } // withdraw ethers function withdrawAll() external onlyAdmin { payable(_fundAddress).transfer(address(this).balance); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; 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; } } // 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 Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; 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; 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 "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } }
admin can set addresses array as MINTER_ROLE
function addToWhitelist(address[] memory _whiteListAddresses) onlyAdmin external { for (uint i = 0; i < _whiteListAddresses.length; i++) { whitelist[_whiteListAddresses[i]] = true; super.grantRole(MINTER_ROLE, _whiteListAddresses[i]); } }
6,849,293
[ 1, 3666, 848, 444, 6138, 526, 487, 6989, 2560, 67, 16256, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9604, 18927, 12, 2867, 8526, 3778, 389, 14739, 682, 7148, 13, 1338, 4446, 3903, 288, 203, 1377, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 14739, 682, 7148, 18, 2469, 31, 277, 27245, 288, 203, 3639, 10734, 63, 67, 14739, 682, 7148, 63, 77, 13563, 273, 638, 31, 203, 3639, 2240, 18, 16243, 2996, 12, 6236, 2560, 67, 16256, 16, 389, 14739, 682, 7148, 63, 77, 19226, 203, 1377, 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 ]
pragma solidity ^0.4.24; interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private admin = msg.sender; address private com = 0xF2bE09314d0F044a537eb4c3d15E2a76feBDD662; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // price to register a name mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it&#39;s simply locking our addresses, // PID&#39;s and names for referral codes. plyr_[1].addr = 0xc49739B31770351D46F73c5E9802d90790aBBCdF; plyr_[1].name = "play"; plyr_[1].names = 1; pIDxAddr_[0xc49739B31770351D46F73c5E9802d90790aBBCdF] = 1; pIDxName_["play"] = 1; plyrNames_[1]["play"] = true; plyrNameList_[1][1] = "play"; pID_ = 1; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you&#39;ve updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn&#39;t exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you&#39;ll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards com.transfer(address(this).balance); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) public { require(msg.sender == admin, "only admin can call"); require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); } function setRegistrationFee(uint256 _fee) public { require(msg.sender == admin, "only admin can call"); registrationFee_ = _fee; } } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
============================================================================== _| _ _|_ _ _ _ _|_ _ . (_|(_| | (_| _\(/_ | |_||_) .=============================|================================================
contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private admin = msg.sender; address private com = 0xF2bE09314d0F044a537eb4c3d15E2a76feBDD662; struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } public constructor() { plyr_[1].addr = 0xc49739B31770351D46F73c5E9802d90790aBBCdF; plyr_[1].name = "play"; plyr_[1].names = 1; pIDxAddr_[0xc49739B31770351D46F73c5E9802d90790aBBCdF] = 1; pIDxName_["play"] = 1; plyrNames_[1]["play"] = true; plyrNameList_[1][1] = "play"; pID_ = 1; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; require(_codeLength == 0, "sorry humans only"); _; } modifier isRegisteredGame() assembly {_codeLength := extcodesize(_addr)} { require(gameIDs_[msg.sender] != 0); _; } ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); event onNewName function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { plyr_[_pID].laff = _affCode; _affCode = 0; } } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { plyr_[_pID].laff = _affCode; _affCode = 0; } } } else if (_affCode == _pID) { registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn&#39;t exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } function useMyOldName(string _nameString) isHuman() public { bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); plyr_[_pID].name = _name; } function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); } function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); } com.transfer(address(this).balance); if (_all == true) emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; return (true); return (false); } } function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; return (true); return (false); } } } else { function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { plyr_[_pID].laff = _affID; _affID = 0; } return(_isNewPlayer, _affID); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { plyr_[_pID].laff = _affID; _affID = 0; } return(_isNewPlayer, _affID); } } else if (_affID == _pID) { registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); function addGame(address _gameAddress, string _gameNameStr) public { require(msg.sender == admin, "only admin can call"); require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); } function setRegistrationFee(uint256 _fee) public { require(msg.sender == admin, "only admin can call"); registrationFee_ = _fee; } }
10,778,121
[ 1, 9917, 26678, 377, 389, 96, 389, 389, 96, 67, 389, 565, 389, 389, 389, 96, 67, 565, 389, 282, 263, 565, 261, 67, 96, 24899, 96, 571, 261, 67, 96, 225, 389, 30351, 18510, 571, 571, 67, 20081, 67, 13, 225, 263, 2429, 14468, 33, 96, 20775, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 19185, 9084, 288, 203, 565, 1450, 1770, 1586, 364, 533, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 3238, 3981, 273, 1234, 18, 15330, 31, 203, 565, 1758, 3238, 532, 273, 374, 16275, 22, 70, 41, 5908, 23, 3461, 72, 20, 42, 3028, 24, 69, 25, 6418, 24008, 24, 71, 23, 72, 3600, 41, 22, 69, 6669, 3030, 38, 5698, 6028, 22, 31, 203, 565, 1958, 19185, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 1731, 1578, 508, 31, 203, 3639, 2254, 5034, 7125, 1403, 31, 203, 3639, 2254, 5034, 1257, 31, 203, 565, 289, 203, 565, 1071, 203, 565, 3885, 1435, 203, 565, 288, 203, 3639, 293, 715, 86, 67, 63, 21, 8009, 4793, 273, 374, 6511, 7616, 27, 5520, 38, 23, 29882, 4630, 10593, 40, 8749, 42, 9036, 71, 25, 41, 10689, 3103, 72, 9349, 7235, 20, 69, 9676, 19728, 42, 31, 203, 3639, 293, 715, 86, 67, 63, 21, 8009, 529, 273, 315, 1601, 14432, 203, 3639, 293, 715, 86, 67, 63, 21, 8009, 1973, 273, 404, 31, 203, 3639, 293, 734, 92, 3178, 67, 63, 20, 6511, 7616, 27, 5520, 38, 23, 29882, 4630, 10593, 40, 8749, 42, 9036, 71, 25, 41, 10689, 3103, 72, 9349, 7235, 20, 69, 9676, 19728, 42, 65, 273, 404, 31, 203, 3639, 293, 734, 92, 461, 67, 9614, 1601, 11929, 273, 404, 31, 203, 3639, 293, 715, 86, 1557, 67, 63, 21, 6362, 6, 1601, 11929, 273, 638, 31, 203, 3639, 293, 715, 86, 461, 682, 67, 2 ]
./full_match/5/0x204Bc468cc9333A7Aac12aC2dBe03DcCFe9f03d0/sources/contracts/protocol/extensions/adapters/AUniswapV3NPM.sol
we make sure we do not clear storage
if (params.amount0Desired > 0) _safeApprove(token0, uniswapNpm, uint256(1));
7,040,050
[ 1, 1814, 1221, 3071, 732, 741, 486, 2424, 2502, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 2010, 18, 8949, 20, 25683, 405, 374, 13, 389, 4626, 12053, 537, 12, 2316, 20, 16, 640, 291, 91, 438, 50, 7755, 16, 2254, 5034, 12, 21, 10019, 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/0xeB40E25AF8F5F22Bb201f53971480beA0094Cd65/sources/src/v0.8/functions/dev/1_0_0/FunctionsRouter.sol
║ The function selector that is used when calling back to the Client contract
bytes4 handleOracleFulfillmentSelector;
4,322,487
[ 1, 163, 248, 244, 1021, 445, 3451, 716, 353, 1399, 1347, 4440, 1473, 358, 326, 2445, 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 ]
[ 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, 1731, 24, 1640, 23601, 23747, 5935, 475, 4320, 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 ]
./partial_match/5/0x7106619Bb2c60ab9d4DAF5FC4941d46cba6Aa4Ed/sources/OOF.sol
* @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); }
16,847,239
[ 1, 6014, 445, 358, 527, 279, 1147, 358, 333, 2710, 1807, 1147, 11093, 501, 12597, 18, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 3096, 358, 326, 2430, 666, 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, 3639, 445, 389, 1289, 1345, 774, 1595, 5157, 21847, 12, 11890, 5034, 1147, 548, 13, 3238, 288, 203, 5411, 389, 454, 5157, 1016, 63, 2316, 548, 65, 273, 389, 454, 5157, 18, 2469, 31, 203, 5411, 389, 454, 5157, 18, 6206, 12, 2316, 548, 1769, 203, 3639, 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 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
углубляться в теорию
rus_verbs:углубляться{},
5,482,945
[ 1, 146, 230, 145, 116, 145, 124, 146, 230, 145, 114, 145, 124, 146, 242, 146, 229, 146, 239, 146, 228, 146, 242, 225, 145, 115, 225, 146, 229, 145, 118, 145, 127, 146, 227, 145, 121, 146, 241, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 436, 407, 67, 502, 2038, 30, 146, 230, 145, 116, 145, 124, 146, 230, 145, 114, 145, 124, 146, 242, 146, 229, 146, 239, 146, 228, 146, 242, 2916, 16, 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 ]
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public{ owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "401: Only the contract owner can call this method."); _; } /** * @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 { if (newOwner != address(0)) { owner = newOwner; } } } contract EthEggBase is Ownable{ enum EggStatus{preSell, selling, brood, finished, notExist} enum MsgType{other, buySuccess, buyFail, sellSuccess, prIncome, chickenDie, eggNotEnough, hatch, moneyIncorrect, prSelf, prNotBuy} struct Egg{ uint64 eggId; uint8 batchNum; EggStatus eggStatus; uint32 chickenId; address eggOwner; } struct Chicken{ uint32 chickenId; uint8 bornNum; address chickenOwner; } Egg[] eggs; Chicken[] chickens; mapping(address=>uint32[]) userToChickenIds; mapping(address=>uint64[]) userToEggIds; //the eggs for user's chicken brood only, not include eggs from buying uint8 currentBatchNum; uint64 currentSellEggIndex; uint256 currentPrice; uint256 initPrice; uint256 eggsCount=1; mapping(address=>uint32) userToChickenCnt; mapping(address=>uint32) userToDeadChickenCnt; mapping(uint8=>uint64) batchNumToCount; uint8 maxHatch; event Message(address _to, uint256 _val1, uint256 _val2, MsgType _msgType, uint64 _msgTime); event DebugBuy(address _to, address _from, uint256 _balance, uint64 _eggId, EggStatus _eggStatus, uint32 _chickenId); function calcPrice() internal { if (currentBatchNum == 0){ currentPrice = initPrice; }else{ currentPrice = initPrice * (9**uint256(currentBatchNum)) / (10**uint256(currentBatchNum)); } } constructor() public { currentBatchNum = 0; maxHatch = 99; //default 99 batchNumToCount[0]=10; //set to 100 default; initPrice = 1000000000000000000; calcPrice(); } function initParams(uint64 _alphaEggCnt) public onlyOwner { require(eggs.length==0); // maxHatch = _maxHatch; //default 99 batchNumToCount[0]=_alphaEggCnt; //set to 100 default; batchNumToCount[1]=_alphaEggCnt; batchNumToCount[2]=batchNumToCount[1]*2; batchNumToCount[3]=batchNumToCount[2]*2; batchNumToCount[4]=batchNumToCount[3]*2; calcBatchCnt(5,50); } //init 100 eggs, price:1 ether function initEggs(uint8 _genAmount) external { require(eggs.length < batchNumToCount[0], "402:Init Eth eggs already generated."); for (uint8 i=1; i <= _genAmount && eggs.length<=batchNumToCount[0]; i++){ uint64 _eggId = uint64(eggs.length + 1); Egg memory _egg = Egg({ eggId:_eggId, batchNum:currentBatchNum, eggStatus:EggStatus.selling, chickenId:0, //that means not egg for any chicken eggOwner:owner //the contract's egg }); eggs.push(_egg); } eggsCount+=_genAmount; } function calcBatchCnt(uint8 _beginIndex, uint8 _endIndex) internal { require (_beginIndex >=5); require (_endIndex <= 50); require (batchNumToCount[_beginIndex]==0); for (uint8 _batchIndex=_beginIndex; _batchIndex< _endIndex; _batchIndex++){ if (batchNumToCount[_batchIndex] == 0){ batchNumToCount[_batchIndex] = batchNumToCount[_batchIndex-1] * 2 - batchNumToCount[_batchIndex-5]; } } } } contract EthEggInfo is EthEggBase { function getPrice() external view returns (uint256){ return currentPrice; } function getEggsCount() public view returns (uint256){ return eggsCount - 1; } function getFarm() external view returns (uint32 [] chickenIds, EggStatus[] eggStatus1, EggStatus[] eggStatus2, EggStatus[] eggStatus3, EggStatus[] eggStatus4 ){ uint32[] memory _chickenIds = userToChickenIds[msg.sender]; EggStatus[] memory _eggStatus1 = new EggStatus[](_getChickenCnt(msg.sender)); EggStatus[] memory _eggStatus2 = new EggStatus[](_getChickenCnt(msg.sender)); EggStatus[] memory _eggStatus3 = new EggStatus[](_getChickenCnt(msg.sender)); EggStatus[] memory _eggStatus4 = new EggStatus[](_getChickenCnt(msg.sender)); for (uint32 _index=0; _index < _chickenIds.length; _index++){ Chicken memory _c = chickens[_chickenIds[_index]-1]; uint8 _maxEggCount=4; uint64[] memory _eggIds = userToEggIds[msg.sender]; for (uint64 j=0; j<_eggIds.length; j++){ Egg memory _e = eggs[_eggIds[j]-1]; if (_c.chickenId == _e.chickenId){ if (_maxEggCount==4){ _eggStatus1[_index] = getEggStatus(_e.eggStatus,_e.batchNum); }else if(_maxEggCount==3){ _eggStatus2[_index] = getEggStatus(_e.eggStatus,_e.batchNum); }else if(_maxEggCount==2){ _eggStatus3[_index] = getEggStatus(_e.eggStatus,_e.batchNum); }else if(_maxEggCount==1){ _eggStatus4[_index] = getEggStatus(_e.eggStatus,_e.batchNum); } _maxEggCount--; } } for (;_maxEggCount>0;_maxEggCount--){ if (_maxEggCount==4){ _eggStatus1[_index] = EggStatus.notExist; }else if(_maxEggCount==3){ _eggStatus2[_index] = EggStatus.notExist; }else if(_maxEggCount==2){ _eggStatus3[_index] = EggStatus.notExist; }else if(_maxEggCount==1){ _eggStatus4[_index] = EggStatus.notExist; } } } chickenIds = _chickenIds; eggStatus1 = _eggStatus1; eggStatus2 = _eggStatus2; eggStatus3 = _eggStatus3; eggStatus4 = _eggStatus4; } function getEggStatus(EggStatus _eggStatus, uint8 _batchNum) internal view returns(EggStatus){ if (_batchNum > currentBatchNum && _eggStatus==EggStatus.selling){ return EggStatus.preSell; }else{ return _eggStatus; } } //The Amount of chicken alive function getChickenAmount() public view returns (uint32){ return userToChickenCnt[msg.sender] - userToDeadChickenCnt[msg.sender]; } //include dead and alive chickens function _getChickenCnt(address _user) internal view returns (uint16){ uint128 _chickenSize = uint128(chickens.length); uint16 _userChickenCnt = 0; for(uint128 i=_chickenSize; i>0; i--){ Chicken memory _c = chickens[i-1]; if (_user == _c.chickenOwner){ _userChickenCnt++; } } return _userChickenCnt; } function getFreeHatchCnt() public view returns(uint32){ return _getFreeHatchCnt(msg.sender); } function _getFreeHatchCnt(address _user) internal view returns(uint32){ uint32 _maxHatch = uint32(maxHatch); if (_maxHatch >= (userToChickenCnt[_user] - userToDeadChickenCnt[_user])){ return _maxHatch - (userToChickenCnt[_user] - userToDeadChickenCnt[_user]); } else { return 0; } } } contract EthEggTx is EthEggInfo{ function buy(uint8 _buyCount) external payable { uint8 _cnt = _buyCount; uint256 _val = msg.value; require(0<_buyCount && _buyCount<=10); if (eggsCount < _cnt){ msg.sender.transfer(_val); emit Message(msg.sender, _val, 0, MsgType.eggNotEnough, uint64(now)); return; } if (getFreeHatchCnt() < _buyCount){ msg.sender.transfer(_val); emit Message(msg.sender, _val, 0, MsgType.hatch, uint64(now)); return; } if (_val != currentPrice * _buyCount){ msg.sender.transfer(_val); emit Message(msg.sender, _val, 0, MsgType.moneyIncorrect, uint64(now)); return; } uint256 _servCharge = 0; for (uint64 i=currentSellEggIndex; i<eggs.length; i++){ Egg storage _egg = eggs[i]; if (getEggStatus(_egg.eggStatus, _egg.batchNum) == EggStatus.preSell){ break; } _egg.eggStatus = EggStatus.brood; address _oldOwner = _egg.eggOwner; _egg.eggOwner = msg.sender; eggsCount--; _oldOwner.transfer(currentPrice * 7 / 10); _servCharge += currentPrice * 3/ 10; chickenBornEgg(_oldOwner, _egg.chickenId); eggBroodToChicken(msg.sender); _cnt--; //send sell success message. emit Message(_oldOwner, currentPrice * 7 / 10, uint256(_egg.chickenId), MsgType.sellSuccess, uint64(now)); if (_cnt<=0){ break; } } currentSellEggIndex = currentSellEggIndex + _buyCount - _cnt; _preSellToSelling(); owner.transfer(_servCharge); //send buy success message. emit Message(msg.sender, _val, uint256(_buyCount - _cnt), MsgType.buySuccess, uint64(now)); } //when user purchase an egg use a promote code function buyWithPr(uint8 _buyCount, address _prUser) external payable{ uint8 _cnt = _buyCount; uint256 _val = msg.value; require(0<_buyCount && _buyCount<=10); if (msg.sender == _prUser){ msg.sender.transfer(_val); emit Message(msg.sender, _val, 0, MsgType.prSelf, uint64(now)); return; } if (userToChickenCnt[_prUser]==0){ msg.sender.transfer(_val); emit Message(msg.sender, _val, 0, MsgType.prNotBuy, uint64(now)); return; } if (eggsCount < _cnt){ msg.sender.transfer(_val); emit Message(msg.sender, _val, 0, MsgType.eggNotEnough, uint64(now)); return; } if (getFreeHatchCnt() < _buyCount){ msg.sender.transfer(_val); emit Message(msg.sender, _val, 0, MsgType.hatch, uint64(now)); return; } if (_val != currentPrice * _buyCount){ msg.sender.transfer(_val); emit Message(msg.sender, _val, 0, MsgType.moneyIncorrect, uint64(now)); return; } uint256 _servCharge = 0; uint256 _prIncome = 0; for (uint64 i=currentSellEggIndex; i<eggs.length; i++){ Egg storage _egg = eggs[i]; if (getEggStatus(_egg.eggStatus, _egg.batchNum) == EggStatus.preSell){ break; } _egg.eggStatus = EggStatus.brood; address _oldOwner = _egg.eggOwner; _egg.eggOwner = msg.sender; eggsCount--; //debug message // emit DebugBuy(msg.sender, _oldOwner, currentPrice, _egg.eggId, getEggStatus(_egg.eggStatus, _egg.batchNum), _egg.chickenId); _oldOwner.transfer(currentPrice * 7 / 10); _prIncome += currentPrice * 8/ 100; _servCharge += currentPrice * 22/ 100; chickenBornEgg(_oldOwner, _egg.chickenId); // userToChickenCnt[msg.sender]++; eggBroodToChicken(msg.sender); _cnt--; //send sell success message. emit Message(_oldOwner, currentPrice * 7 / 10, uint256(_egg.chickenId), MsgType.sellSuccess, uint64(now)); if (_cnt<=0){ break; } } currentSellEggIndex = currentSellEggIndex + _buyCount - _cnt; _preSellToSelling(); _prUser.transfer(_prIncome); owner.transfer(_servCharge); //send pr message. emit Message(_prUser, _prIncome, uint256(_buyCount - _cnt), MsgType.prIncome, uint64(now)); //send buy success message. emit Message(msg.sender, _val, uint256(_buyCount - _cnt), MsgType.buySuccess, uint64(now)); } function chickenBornEgg(address _user, uint32 _chickenId) internal { if (_user == owner){ return; } if (_chickenId == 0){ return; } Chicken storage _chicken = chickens[_chickenId-1]; if (_chicken.bornNum < 4){ _chicken.bornNum++; uint64 _eggId = uint64(eggs.length+1); uint8 _batchNum = _getBatchNumByEggId(_eggId); EggStatus _status = EggStatus.selling; Egg memory _egg = Egg({ eggId: _eggId, batchNum: _batchNum, eggStatus: _status, chickenId: _chickenId, eggOwner: _user }); eggs.push(_egg); userToEggIds[_user].push(_eggId); } else if (_chicken.bornNum == 4){ userToDeadChickenCnt[_user]++; emit Message(_chicken.chickenOwner, uint256(_chickenId), uint256(_chicken.chickenId), MsgType.chickenDie, uint64(now)); } } function eggBroodToChicken(address _user) internal { if (owner != _user && _getFreeHatchCnt(_user) > 0){ uint32 _chickenId = uint32(chickens.length+1); Chicken memory _chicken = Chicken({ chickenId:_chickenId, bornNum:0, chickenOwner:_user }); chickens.push(_chicken); userToChickenCnt[_user]++; userToChickenIds[_user].push(_chickenId); //and then the chicken generate an egg. chickenBornEgg(_user, _chickenId); } } function _preSellToSelling() internal { if (getEggsCount()==0){ currentBatchNum++; uint64 _cnt = 0; for(uint64 _index = currentSellEggIndex; _index < eggs.length; _index++){ Egg memory _egg = eggs[_index]; if (getEggStatus(_egg.eggStatus, _egg.batchNum) == EggStatus.preSell){ break; } if (getEggStatus(_egg.eggStatus, _egg.batchNum) == EggStatus.selling){ _cnt++; } } eggsCount = eggsCount + _cnt; if (getEggsCount()>0){ calcPrice(); } } } function _getBatchNumByEggId(uint64 _eggId) internal view returns(uint8){ int128 _count = int128(_eggId); uint8 _batchNo = 0; for(;_batchNo<=49;_batchNo++){ _count = _count - int128(batchNumToCount[_batchNo]); if (_count <= 0){ break; } } return _batchNo; } function testEggIds() public view returns(uint64[]){ uint64[] memory _ids = new uint64[](eggs.length); for(uint64 i=0; i < uint64(eggs.length); i++){ _ids[i] = eggs[i].eggId; } return _ids; } function testChickenInfo(uint32 _chickenId) public view returns(uint32, uint8, address){ require(_chickenId>0); Chicken memory _chicken = chickens[_chickenId-1]; return (_chicken.chickenId, _chicken.bornNum, _chicken.chickenOwner); } function testEggInfo(uint64 _eggId) public view returns(uint64 cid, uint8 batchNum, EggStatus eggStatus, uint32 chickenId, address eggOwner){ require(_eggId>0); Egg memory _egg = eggs[_eggId-1]; uint8 _batchNum = _egg.batchNum; EggStatus _eggStatus = getEggStatus(_egg.eggStatus, _egg.batchNum); uint32 _chickenId = _egg.chickenId; address _eggOwner = _egg.eggOwner; return (_eggId, _batchNum, _eggStatus, _chickenId, _eggOwner); } function testChickenCnt() external view returns(uint32){ return userToChickenCnt[msg.sender]; } function testDeadChickenCnt() external view returns(uint32){ return userToDeadChickenCnt[msg.sender]; } }
init 100 eggs, price:1 ether
function initEggs(uint8 _genAmount) external { require(eggs.length < batchNumToCount[0], "402:Init Eth eggs already generated."); for (uint8 i=1; i <= _genAmount && eggs.length<=batchNumToCount[0]; i++){ uint64 _eggId = uint64(eggs.length + 1); Egg memory _egg = Egg({ eggId:_eggId, batchNum:currentBatchNum, eggStatus:EggStatus.selling, }); eggs.push(_egg); } eggsCount+=_genAmount; }
14,049,497
[ 1, 2738, 2130, 9130, 564, 16, 6205, 30, 21, 225, 2437, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 29731, 75, 564, 12, 11890, 28, 389, 4507, 6275, 13, 3903, 288, 203, 3639, 2583, 12, 1332, 564, 18, 2469, 411, 2581, 2578, 774, 1380, 63, 20, 6487, 315, 24, 3103, 30, 2570, 512, 451, 9130, 564, 1818, 4374, 1199, 1769, 203, 203, 3639, 364, 261, 11890, 28, 277, 33, 21, 31, 277, 1648, 389, 4507, 6275, 597, 9130, 564, 18, 2469, 32, 33, 5303, 2578, 774, 1380, 63, 20, 15533, 277, 27245, 95, 203, 5411, 2254, 1105, 389, 23171, 548, 273, 2254, 1105, 12, 1332, 564, 18, 2469, 397, 404, 1769, 203, 5411, 512, 14253, 3778, 389, 23171, 273, 512, 14253, 12590, 203, 7734, 25144, 548, 30, 67, 23171, 548, 16, 203, 7734, 2581, 2578, 30, 2972, 4497, 2578, 16, 203, 7734, 25144, 1482, 30, 41, 14253, 1482, 18, 87, 1165, 310, 16, 203, 7734, 15549, 203, 5411, 9130, 564, 18, 6206, 24899, 23171, 1769, 203, 3639, 289, 203, 3639, 9130, 564, 1380, 15, 33, 67, 4507, 6275, 31, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/BARConsoles.sol pragma solidity ^0.8.7; // IMPORTS // /** * @dev ERC721 token standard */ /** * @dev Modifier 'onlyOwner' becomes available, where owner is the contract deployer */ // CONTRACT // contract BARConsoles is ERC721Enumerable, Ownable { uint256 private currentTokenId = 1; uint256 public MAX_SUPPLY = 2000; uint256 public cost = 60000000000000000; // cost of minting in Wei, equivalent to 0.04 ether uint256 private preSaleMintsTotal; string private baseTokenURI; bool public preSaleStatus = false; bool public generalSaleStatus = false; bool public claimStatus = false; constructor( string memory _name, string memory _symbol, string memory _uri ) ERC721(_name, _symbol) { baseTokenURI = _uri; } // EVENTS // event TokenBought(uint256 tokenId); // MAPPINGS // mapping(address => uint) whitelist; mapping(address => bool) claimList; // PUBLIC // /** * @dev Mint a token through pre or general sale * @param _num - number of tokens to mint */ function mint(uint256 _num) external payable { require(msg.value == _num * cost, "Incorrect funds supplied"); // mint cost if (preSaleStatus == true) { require(_num > 0 && _num <=2, "2 mint maximum"); require(whitelist[msg.sender] >= _num, "Not on whitelist or maximum of 2 mints per address allowed"); // checks if white listed & mint limit per address is obeyed require(preSaleMintsTotal + _num <= 500, "Minting that many would exceed pre sale minting allocation"); // ensures pre sale total mint limit is obeyed whitelist[msg.sender] -= _num; // reduces caller's minting allownace by the number of tokens they minted preSaleMintsTotal += _num; } else { require(generalSaleStatus, "It's not time yet"); // checks general sale is live require(_num > 0 && _num <= 3, "Maximum of 3 mints allowed"); // mint limit per tx } for (uint256 i = 0; i < _num; i++) { uint tokenId = currentTokenId; require(tokenId <= MAX_SUPPLY, "All tokens have been minted"); currentTokenId++; _mint(msg.sender, tokenId); emit TokenBought(tokenId); } } /** * @dev Mint token if on pre approved 'claimList' */ function claim() external { require(claimStatus, "It's not time yet"); // ensures claiming is live require(claimList[msg.sender], "Not on pre-approved claim list or have already claimed"); uint tokenId = currentTokenId; require(tokenId <= MAX_SUPPLY, "All tokens have been minted"); currentTokenId++; claimList[msg.sender] = false; // ensures they cannot claim a token a second time _mint(msg.sender, tokenId); emit TokenBought(tokenId); } // VIEW // /** * @dev Returns tokenURI, which is comprised of the baseURI concatenated with the tokenId */ function tokenURI(uint256 _tokenId) public view override returns(string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); } // ONLY OWNER // /** * @dev Withdraw ether from smart contract. Only contract owner can call. * @param _to - address ether will be sent to * @param _amount - amount of ether, in Wei, to be withdrawn (1 wei = 1e-18 ether) */ function withdrawFunds(address payable _to, uint _amount) external onlyOwner { require(_amount <= address(this).balance, "Withdrawal amount greater than balance"); _to.transfer(_amount); } /** * @dev Withdraw all ether from smart contract. Only contract owner can call. * @param _to - address ether will be sent to */ function withdrawAllFunds(address payable _to) external onlyOwner { require(address(this).balance > 0, "No funds to withdraw"); _to.transfer(address(this).balance); } /** * @dev Add addresses to white list, giving access to mint 2 tokens at pre sale * @param _addresses - array of address' to add to white list mapping */ function whitelistAddresses(address[] calldata _addresses) external onlyOwner { for (uint i=0; i<_addresses.length; i++) { whitelist[_addresses[i]] = 2; } } /** * @dev Add addresses to claim list, giving access to claim function * @param _addresses - array of address' to add to claim list mapping */ function claimAddresses(address[] calldata _addresses) external onlyOwner { for (uint i=0; i<_addresses.length; i++) { claimList[_addresses[i]] = true; } } /** * @dev Airdrop 1 token to each address in array '_to' * @param _to - array of address' that tokens will be sent to */ function airDrop(address[] calldata _to) external onlyOwner { for (uint i=0; i<_to.length; i++) { uint tokenId = currentTokenId; require(tokenId <= MAX_SUPPLY, "All tokens have been minted"); currentTokenId++; _mint(_to[i], tokenId); emit TokenBought(tokenId); } } /** * @dev Set the baseURI string */ function setBaseUri(string memory _newBaseUri) external onlyOwner { baseTokenURI = _newBaseUri; } /** * @dev Set the cost of minting a token * @param _newCost in Wei. Where 1 Wei = 10^-18 ether */ function setCost(uint _newCost) external onlyOwner { cost = _newCost; } /** * @dev Set the status of the pre sale * @param _status boolean where true = live */ function setPreSaleStatus(bool _status) external onlyOwner { preSaleStatus = _status; } /** * @dev Set the status of the general sale * @param _status boolean where true = live */ function setGeneralSaleStatus(bool _status) external onlyOwner { generalSaleStatus = _status; } /** * @dev Set the status of claim minitng * @param _status boolean where true = live */ function setClaimStatus(bool _status) external onlyOwner { claimStatus = _status; } /** * @dev Change the pre sale and claim status to over (false), and general sale status to live (true) */ function switchPreToGeneral() external onlyOwner { claimStatus = false; preSaleStatus = false; generalSaleStatus = true; } }
* @dev Add addresses to claim list, giving access to claim function @param _addresses - array of address' to add to claim list mapping/
function claimAddresses(address[] calldata _addresses) external onlyOwner { for (uint i=0; i<_addresses.length; i++) { claimList[_addresses[i]] = true; } }
9,824,249
[ 1, 986, 6138, 358, 7516, 666, 16, 21057, 2006, 358, 7516, 445, 225, 389, 13277, 300, 526, 434, 1758, 11, 358, 527, 358, 7516, 666, 2874, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 7148, 12, 2867, 8526, 745, 892, 389, 13277, 13, 3903, 1338, 5541, 288, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 32, 67, 13277, 18, 2469, 31, 277, 27245, 288, 203, 5411, 7516, 682, 63, 67, 13277, 63, 77, 13563, 273, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]